Created
October 10, 2017 11:01
-
-
Save whatalnk/07983e9cde5f2d06f593fccc8f204193 to your computer and use it in GitHub Desktop.
AtCoder ARC #030 B - ツリーグラフ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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