結果

問題 No.1637 Easy Tree Query
ユーザー 小野寺健
提出日時 2021-11-01 16:59:35
言語 Ruby
(3.4.1)
結果
AC  
実行時間 689 ms / 2,000 ms
コード長 634 bytes
コンパイル時間 499 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 31,360 KB
最終ジャッジ日時 2024-10-10 07:30:03
合計ジャッジ時間 17,077 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 33
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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
}
0