結果

問題 No.1484 木に数を書き込む問題 / Just Write Numbers! 2
ユーザー maguroflymagurofly
提出日時 2021-12-15 02:08:58
言語 Ruby
(3.3.0)
結果
AC  
実行時間 1,011 ms / 2,000 ms
コード長 577 bytes
コンパイル時間 354 ms
コンパイル使用メモリ 11,336 KB
実行使用メモリ 59,900 KB
最終ジャッジ日時 2023-10-01 02:21:07
合計ジャッジ時間 21,054 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 83 ms
15,176 KB
testcase_01 AC 80 ms
15,244 KB
testcase_02 AC 81 ms
15,080 KB
testcase_03 AC 80 ms
15,052 KB
testcase_04 AC 90 ms
15,416 KB
testcase_05 AC 132 ms
17,928 KB
testcase_06 AC 145 ms
18,176 KB
testcase_07 AC 109 ms
16,596 KB
testcase_08 AC 145 ms
18,692 KB
testcase_09 AC 136 ms
18,368 KB
testcase_10 AC 132 ms
17,920 KB
testcase_11 AC 127 ms
18,076 KB
testcase_12 AC 120 ms
17,112 KB
testcase_13 AC 85 ms
15,184 KB
testcase_14 AC 801 ms
48,164 KB
testcase_15 AC 772 ms
47,228 KB
testcase_16 AC 710 ms
45,424 KB
testcase_17 AC 528 ms
37,788 KB
testcase_18 AC 839 ms
49,992 KB
testcase_19 AC 993 ms
59,764 KB
testcase_20 AC 986 ms
59,752 KB
testcase_21 AC 993 ms
59,872 KB
testcase_22 AC 988 ms
59,704 KB
testcase_23 AC 1,011 ms
59,740 KB
testcase_24 AC 987 ms
59,720 KB
testcase_25 AC 1,003 ms
59,872 KB
testcase_26 AC 984 ms
59,900 KB
testcase_27 AC 982 ms
59,880 KB
testcase_28 AC 989 ms
59,728 KB
testcase_29 AC 700 ms
55,600 KB
testcase_30 AC 742 ms
55,616 KB
testcase_31 AC 717 ms
59,076 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

N = gets.to_i
graph = Array.new(N) { [] }
sum = 0
(N - 1).times do
  a, b = gets.split.map(&:to_i)
  sum += 1
  graph[a - 1] << [b - 1, 1]
  graph[b - 1] << [a - 1, 1]
end

dfs = ->(start) {
  visited = Array.new(N, false)
  visited[start] = true
  dist = Array.new(N, nil)
  dist[start] = 0
  stack = [start]
  while (u = stack.pop)
    graph[u].each do |v, c|
      next if visited[v]
      visited[v] = true
      dist[v] = dist[u] + c
      stack << v
    end
  end
  dist
}

d1 = dfs[0]
max = d1.max
v = d1.index(max)
d2 = dfs[v]
diameter = d2.max

puts sum * 2 - diameter
0