N, Q = gets.split(" ").map{|s| s.to_i} v = Array.new(N) {Array.new} (N-1).times { a, b = gets.split(" ").map{|s| s.to_i} v[b-1] << a-1 v[a-1] << b-1 } q = [] Q.times { q << gets.split(" ").map{|s| s.to_i} } stack = [] stack << [-1, 0] sorted_nodes = [] until stack.empty? parent, node = stack.pop sorted_nodes << node v[node].each do |child| stack << [node, child] if child != parent end end counts = Array.new(N, 0) sorted_nodes.reverse_each do |node| ret = 1 v[node].each do |child| ret += counts[child] end counts[node] = ret end total = 0 q.each {|p, x| total += counts[p-1] * x puts total }