結果

問題 No.277 根掘り葉掘り
ユーザー らっしー(raccy)らっしー(raccy)
提出日時 2017-03-12 10:40:28
言語 Ruby
(3.3.0)
結果
AC  
実行時間 535 ms / 3,000 ms
コード長 722 bytes
コンパイル時間 53 ms
コンパイル使用メモリ 11,368 KB
実行使用メモリ 34,232 KB
最終ジャッジ日時 2023-09-07 11:06:33
合計ジャッジ時間 7,757 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 85 ms
15,148 KB
testcase_01 AC 82 ms
15,252 KB
testcase_02 AC 80 ms
15,088 KB
testcase_03 AC 83 ms
15,288 KB
testcase_04 AC 84 ms
15,308 KB
testcase_05 AC 86 ms
15,084 KB
testcase_06 AC 83 ms
15,260 KB
testcase_07 AC 81 ms
15,136 KB
testcase_08 AC 81 ms
15,128 KB
testcase_09 AC 474 ms
27,504 KB
testcase_10 AC 460 ms
33,368 KB
testcase_11 AC 497 ms
31,096 KB
testcase_12 AC 474 ms
32,440 KB
testcase_13 AC 530 ms
33,368 KB
testcase_14 AC 507 ms
34,232 KB
testcase_15 AC 518 ms
33,232 KB
testcase_16 AC 523 ms
30,740 KB
testcase_17 AC 535 ms
33,840 KB
testcase_18 AC 519 ms
30,688 KB
testcase_19 AC 500 ms
33,480 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

# frozen_string_literal: true
n = gets.to_i
edges = {}
(n - 1).times do
  x, y = gets.split.map(&:to_i)
  (edges[x] ||= []) << y
  (edges[y] ||= []) << x
end

root_node = 1
leaf_nodes = edges.find_all { |_k, v| v.length == 1 }
  .map(&:first) - [root_node]
zero_nodes = [root_node] + leaf_nodes

node_lengths = Array.new(n + 1)
checked_nodes = Array.new(n + 1) { false }
queue = []

zero_nodes.each do |rl|
  queue << rl
  checked_nodes[rl] = true
  node_lengths[rl] = 0
end

while (i = queue.shift)
  next_root_length = node_lengths[i] + 1
  edges[i].each do |t|
    next if checked_nodes[t]
    queue << t
    checked_nodes[t] = true
    node_lengths[t] = next_root_length
  end
end
node_lengths.shift
puts node_lengths
0