結果
問題 | No.277 根掘り葉掘り |
ユーザー |
|
提出日時 | 2017-03-12 10:21:32 |
言語 | Ruby (3.4.1) |
結果 |
TLE
|
実行時間 | - |
コード長 | 1,317 bytes |
コンパイル時間 | 209 ms |
コンパイル使用メモリ | 7,424 KB |
実行使用メモリ | 37,280 KB |
最終ジャッジ日時 | 2024-06-25 05:16:57 |
合計ジャッジ時間 | 6,110 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 7 TLE * 1 -- * 10 |
コンパイルメッセージ
Syntax OK
ソースコード
# frozen_string_literal: true n = gets.to_i edges = Array.new(n - 1) { gets.split.map(&:to_i) } root_node = 1 leaf_nodes = edges.flatten .group_by(&:itself) .find_all { |_k, v| v.length == 1 } .map(&:first) - [root_node] root_lengths = Array.new(n + 1) checked_nodes = Array.new(n + 1) { false } queue = [] queue << 1 checked_nodes[1] = true root_lengths[1] = 0 while (i = queue.shift) next_root_length = root_lengths[i] + 1 edges.each do |x, y| if x == i t = y elsif y == i t = x else next end next if checked_nodes[t] queue << t checked_nodes[t] = true root_lengths[t] = next_root_length end end leaf_nodes.each do |l| checked_nodes = Array.new(n + 1) { false } leaf_lengths = Array.new(n + 1) queue = [] queue << l checked_nodes[l] = true leaf_lengths[l] = 0 root_lengths[l] = 0 while (i = queue.shift) next_leaf_length = leaf_lengths[i] + 1 edges.each do |x, y| if x == i t = y elsif y == i t = x else next end next if checked_nodes[t] checked_nodes[t] = true next if root_lengths[t] < next_leaf_length queue << t leaf_lengths[t] = next_leaf_length root_lengths[t] = next_leaf_length end end end root_lengths.shift puts root_lengths