結果

問題 No.277 根掘り葉掘り
ユーザー 👑 obakyanobakyan
提出日時 2019-06-03 09:16:42
言語 Lua
(LuaJit 2.0.5)
結果
AC  
実行時間 218 ms / 3,000 ms
コード長 1,140 bytes
コンパイル時間 38 ms
使用メモリ 15,952 KB
最終ジャッジ日時 2023-03-03 04:37:05
合計ジャッジ時間 3,841 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
使用メモリ
testcase_00 AC 1 ms
6,256 KB
testcase_01 AC 1 ms
6,220 KB
testcase_02 AC 1 ms
6,256 KB
testcase_03 AC 2 ms
6,200 KB
testcase_04 AC 1 ms
6,168 KB
testcase_05 AC 1 ms
6,276 KB
testcase_06 AC 1 ms
6,168 KB
testcase_07 AC 2 ms
6,324 KB
testcase_08 AC 1 ms
6,196 KB
testcase_09 AC 182 ms
14,332 KB
testcase_10 AC 163 ms
15,696 KB
testcase_11 AC 203 ms
15,952 KB
testcase_12 AC 183 ms
15,120 KB
testcase_13 AC 218 ms
15,368 KB
testcase_14 AC 188 ms
15,404 KB
testcase_15 AC 189 ms
15,260 KB
testcase_16 AC 196 ms
15,244 KB
testcase_17 AC 182 ms
15,204 KB
testcase_18 AC 188 ms
15,204 KB
testcase_19 AC 184 ms
15,224 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

local n = io.read("*n")
local t = {}
local fromroot = {}
local fromleaf = {}
for i = 1, n do
  t[i] = {}
  fromroot[i] = -1
  fromleaf[i] = -1
end
for i = 1, n - 1 do
  local a, b = io.read("*n", "*n")
  table.insert(t[a], b)
  table.insert(t[b], a)
end

local tasks = {1}
local tasknum, done = 1, 0
fromroot[1] = 0
while done < tasknum do
  done = done + 1
  local curidx = tasks[done]
  for i = 1, #t[curidx] do
    local nextidx = t[curidx][i]
    if fromroot[nextidx] == -1 then
      fromroot[nextidx] = fromroot[curidx] + 1
      tasknum = tasknum + 1
      table.insert(tasks, nextidx)
    end
  end
end

tasks = {}
tasknum, done = 0, 0
for i = 1, n do
  if #t[i] == 1 then
    tasknum = tasknum + 1
    table.insert(tasks, i)
    fromleaf[i] = 0
  end
end

while done < tasknum do
  done = done + 1
  local curidx = tasks[done]
  for i = 1, #t[curidx] do
    local nextidx = t[curidx][i]
    if fromleaf[nextidx] == -1 then
      fromleaf[nextidx] = fromleaf[curidx] + 1
      tasknum = tasknum + 1
      table.insert(tasks, nextidx)
    end
  end
end
local mmi = math.min
for i = 1, n do
  print(mmi(fromroot[i], fromleaf[i]))
end
0