結果

問題 No.277 根掘り葉掘り
ユーザー らっしー(raccy)らっしー(raccy)
提出日時 2017-03-12 10:21:32
言語 Ruby
(3.2.2)
結果
TLE  
実行時間 -
コード長 1,317 bytes
コンパイル時間 178 ms
コンパイル使用メモリ 11,244 KB
実行使用メモリ 39,204 KB
最終ジャッジ日時 2023-09-07 11:06:17
合計ジャッジ時間 6,056 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 80 ms
15,244 KB
testcase_01 AC 80 ms
15,016 KB
testcase_02 AC 81 ms
15,344 KB
testcase_03 AC 85 ms
15,248 KB
testcase_04 AC 87 ms
15,084 KB
testcase_05 AC 85 ms
15,152 KB
testcase_06 AC 96 ms
15,268 KB
testcase_07 AC 88 ms
15,244 KB
testcase_08 AC 82 ms
15,164 KB
testcase_09 TLE -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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