Skip to content

Instantly share code, notes, and snippets.

@whatalnk
Created October 10, 2017 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whatalnk/07983e9cde5f2d06f593fccc8f204193 to your computer and use it in GitHub Desktop.
Save whatalnk/07983e9cde5f2d06f593fccc8f204193 to your computer and use it in GitHub Desktop.
AtCoder ARC #030 B - ツリーグラフ
n, x = gets.chomp.split(" ").map(&:to_i)
node = Struct.new("Node", :to)
@h = [0] + gets.chomp.split(" ").map(&:to_i)
@g = Array.new(n+1){node.new([])}
(n-1).times do
a, b = gets.chomp.split(" ").map(&:to_i)
@g[a].to << b
@g[b].to << a
end
def jewel(v, root, from)
cost = 0
@g[v].to.each do |i|
next if i == from
cost += jewel(i, root, v)
end
# Root
return cost if v == root
# Leaf
return cost + @h[v] if cost == 0
# Other
return cost + 1
end
puts jewel(x, x, -1) * 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment