Skip to content

Instantly share code, notes, and snippets.

@whatalnk
Last active September 21, 2017 09:45
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/82c2abae7b33138740f56a30d7d5dca9 to your computer and use it in GitHub Desktop.
Save whatalnk/82c2abae7b33138740f56a30d7d5dca9 to your computer and use it in GitHub Desktop.
AtCoder ABC #070 D
# AC
n = gets.chomp.to_i
edge = Struct.new("Edge", :to, :cost)
tree = Array.new(n+1){Array.new()}
depth = Array.new(n+1)
(n - 1).times do
a, b, c = gets.chomp.split(" ").map(&:to_i)
a -= 1
b -= 1
tree[a] << edge.new(b, c)
tree[b] << edge.new(a, c)
end
q, k = gets.chomp.split(" ").map(&:to_i)
k -= 1
depth[k] = 0
cand = [[k, 0]]
while cand.length > 0
curr, dist = cand.shift
tree[curr].each do |e|
unless depth[e.to]
depth[e.to] = dist + e.cost
cand << [e.to, depth[e.to]]
end
end
end
q.times do
x, y = gets.chomp.split(" ").map(&:to_i)
x -= 1
y -= 1
puts depth[x] + depth[y]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment