結果

問題 No.1488 Max Score of the Tree
ユーザー 👑 obakyanobakyan
提出日時 2021-04-30 20:09:21
言語 Lua
(LuaJit 2.1.1696795921)
結果
AC  
実行時間 16 ms / 2,000 ms
コード長 1,426 bytes
コンパイル時間 182 ms
コンパイル使用メモリ 5,216 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-25 22:17:42
合計ジャッジ時間 2,195 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 13 ms
4,376 KB
testcase_01 AC 14 ms
4,376 KB
testcase_02 AC 15 ms
4,380 KB
testcase_03 AC 14 ms
4,376 KB
testcase_04 AC 15 ms
4,380 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 5 ms
4,376 KB
testcase_07 AC 9 ms
4,376 KB
testcase_08 AC 6 ms
4,380 KB
testcase_09 AC 6 ms
4,376 KB
testcase_10 AC 9 ms
4,380 KB
testcase_11 AC 14 ms
4,380 KB
testcase_12 AC 1 ms
4,380 KB
testcase_13 AC 4 ms
4,376 KB
testcase_14 AC 8 ms
4,376 KB
testcase_15 AC 5 ms
4,380 KB
testcase_16 AC 3 ms
4,376 KB
testcase_17 AC 4 ms
4,376 KB
testcase_18 AC 10 ms
4,376 KB
testcase_19 AC 6 ms
4,380 KB
testcase_20 AC 3 ms
4,376 KB
testcase_21 AC 2 ms
4,376 KB
testcase_22 AC 5 ms
4,376 KB
testcase_23 AC 1 ms
4,380 KB
testcase_24 AC 1 ms
4,376 KB
testcase_25 AC 1 ms
4,380 KB
testcase_26 AC 5 ms
4,380 KB
testcase_27 AC 2 ms
4,380 KB
testcase_28 AC 3 ms
4,376 KB
testcase_29 AC 3 ms
4,376 KB
testcase_30 AC 12 ms
4,380 KB
testcase_31 AC 16 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

local mmi, mma = math.min, math.max
local n, k = io.read("*n", "*n")
local edge = {}
local parent = {}
local childcnt = {}
local weight = {}
local len = {}
local base = 0
for i = 1, n do
  edge[i] = {}
  parent[i] = 0
  childcnt[i] = 0
  weight[i] = 0
  len[i] = 0
end
for i = 1, n - 1 do
  local a, b, c = io.read("*n", "*n", "*n")
  edge[a][b] = c
  edge[b][a] = c
end
local tasks = {1}
for i = 1, n do 
  local src = tasks[i]
  for dst, l in pairs(edge[src]) do
    if parent[src] ~= dst then
      parent[dst] = src
      len[dst] = len[src] + l
      childcnt[src] = childcnt[src] + 1
      table.insert(tasks, dst)
    end
  end
end
local edgecost, edgevalue = {}, {}
tasks = {}
for i = 1, n do
  if childcnt[i] == 0 then
    table.insert(tasks, i)
    weight[i] = 1
    base = base + len[i]
  end
end

for i = 1, n - 1 do
  local child = tasks[i]
  local p = parent[child]
  table.insert(edgecost, edge[child][p])
  table.insert(edgevalue, edge[child][p] * weight[child])
  weight[p] = weight[p] + weight[child]
  childcnt[p] = childcnt[p] - 1
  if childcnt[p] == 0 then
    table.insert(tasks, p)
  end
end
local dp = {}
for i = 1, k do
  dp[i] = 0
end

for i = 1, n - 1 do
  local c, v = edgecost[i], edgevalue[i]
  for j = k - c, 1, -1 do
    dp[j + c] = mma(dp[j + c], dp[j] + v)
  end
  if c <= k then
    dp[c] = mma(dp[c], v)
  end
end
local ret = 0
for i = 1, k do
  ret = mma(ret, dp[i])
end
print(ret + base)
0