結果

問題 No.1418 Sum of Sum of Subtree Size
ユーザー 👑 obakyanobakyan
提出日時 2021-07-22 00:22:30
言語 Lua
(LuaJit 2.1.1696795921)
結果
AC  
実行時間 147 ms / 2,000 ms
コード長 1,140 bytes
コンパイル時間 98 ms
コンパイル使用メモリ 5,336 KB
実行使用メモリ 17,068 KB
最終ジャッジ日時 2023-09-24 13:38:54
合計ジャッジ時間 3,799 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 KB
testcase_01 AC 1 ms
4,384 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 143 ms
16,968 KB
testcase_04 AC 147 ms
16,948 KB
testcase_05 AC 144 ms
16,968 KB
testcase_06 AC 144 ms
17,068 KB
testcase_07 AC 137 ms
16,948 KB
testcase_08 AC 91 ms
14,660 KB
testcase_09 AC 40 ms
6,464 KB
testcase_10 AC 47 ms
8,560 KB
testcase_11 AC 25 ms
5,364 KB
testcase_12 AC 70 ms
10,008 KB
testcase_13 AC 81 ms
10,784 KB
testcase_14 AC 90 ms
14,556 KB
testcase_15 AC 69 ms
9,780 KB
testcase_16 AC 9 ms
4,376 KB
testcase_17 AC 9 ms
4,376 KB
testcase_18 AC 130 ms
16,356 KB
testcase_19 AC 24 ms
5,420 KB
testcase_20 AC 5 ms
4,376 KB
testcase_21 AC 62 ms
9,664 KB
testcase_22 AC 54 ms
9,128 KB
testcase_23 AC 6 ms
4,380 KB
testcase_24 AC 6 ms
4,380 KB
testcase_25 AC 5 ms
4,376 KB
testcase_26 AC 6 ms
4,380 KB
testcase_27 AC 2 ms
4,376 KB
testcase_28 AC 3 ms
4,376 KB
testcase_29 AC 8 ms
4,380 KB
testcase_30 AC 8 ms
4,380 KB
testcase_31 AC 5 ms
4,376 KB
testcase_32 AC 6 ms
4,376 KB
testcase_33 AC 23 ms
5,740 KB
testcase_34 AC 109 ms
16,340 KB
testcase_35 AC 44 ms
8,860 KB
testcase_36 AC 13 ms
4,380 KB
testcase_37 AC 103 ms
17,016 KB
testcase_38 AC 95 ms
16,668 KB
testcase_39 AC 1 ms
4,376 KB
testcase_40 AC 1 ms
4,380 KB
testcase_41 AC 1 ms
4,376 KB
testcase_42 AC 1 ms
4,376 KB
testcase_43 AC 2 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

local n = io.read("*n")
local edge = {}
local parent = {}
local childcnt = {}
local w = {}
local asked = {}
for i = 1, n do
  edge[i] = {}
  parent[i] = 0
  childcnt[i] = 0
  w[i] = 1
  asked[i] = false
end
for i = 1, n - 1 do
  local p, q = io.read("*n", "*n")
  table.insert(edge[p], q)
  table.insert(edge[q], p)
end
local tasks = {1}
asked[1] = true
for i = 1, n do
  local src = tasks[i]
  for j = 1, #edge[src] do
    local dst = edge[src][j]
    if not asked[dst] then
      asked[dst] = true
      childcnt[src] = childcnt[src] + 1
      table.insert(tasks, dst)
      parent[dst] = src
    end
  end
end

local ret = n * n
tasks = {}
for i = 1, n do
  if childcnt[i] == 0 then table.insert(tasks, i) end
end
for i = 1, n do
  local src = tasks[i]
  ret = ret + (n - w[src]) * w[src]
  local p = parent[src]
  for j = 1, #edge[src] do
    local dst = edge[src][j]
    if dst ~= p then
      ret = ret + w[dst] * (n - w[dst])
    end
  end
  if 0 < p then
    childcnt[p] = childcnt[p] - 1
    if childcnt[p] == 0 then table.insert(tasks, p) end
    w[p] = w[p] + w[src]
  end
end
ret = tostring(1LL * ret):gsub("LL", "")
print(ret)
0