結果

問題 No.872 All Tree Path
ユーザー ikdikd
提出日時 2020-04-09 08:14:15
言語 Nim
(2.0.2)
結果
AC  
実行時間 212 ms / 3,000 ms
コード長 1,222 bytes
コンパイル時間 4,576 ms
コンパイル使用メモリ 68,312 KB
実行使用メモリ 54,632 KB
最終ジャッジ日時 2023-09-27 11:15:54
合計ジャッジ時間 7,302 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 196 ms
41,140 KB
testcase_01 AC 200 ms
40,512 KB
testcase_02 AC 206 ms
40,308 KB
testcase_03 AC 131 ms
54,632 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 200 ms
40,580 KB
testcase_06 AC 201 ms
41,712 KB
testcase_07 AC 212 ms
41,048 KB
testcase_08 AC 16 ms
6,436 KB
testcase_09 AC 15 ms
6,444 KB
testcase_10 AC 14 ms
6,464 KB
testcase_11 AC 14 ms
6,452 KB
testcase_12 AC 14 ms
6,396 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 1 ms
4,376 KB
testcase_15 AC 2 ms
4,376 KB
testcase_16 AC 1 ms
4,376 KB
testcase_17 AC 2 ms
4,380 KB
testcase_18 AC 1 ms
4,380 KB
testcase_19 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import strutils, sequtils, deques, math

let read = iterator: string {.closure.} =
  for s in stdin.readAll.split:
    yield s

proc main() =
  let n = read().parseInt
  type E = tuple[to, cost: int]
  var g = newSeqWith(n, newSeq[E]())
  for i in 1..<n:
    let a, b, c = read().parseInt
    g[a - 1].add((b - 1, c))
    g[b - 1].add((a - 1, c))
  # 0 を根とする
  # size[i]: 部分木 i に含まれる頂点数
  # dp[i]: Σd(i, i の子孫)
  var
    size = newSeq[int](n)
    dp = newSeq[int](n)
  proc dfs(i, p: int) =
    size[i] = 1
    for e in g[i]:
      if e.to != p:
        dfs(e.to, i)
        size[i] += size[e.to]
        dp[i] += dp[e.to] + size[e.to] * e.cost
  dfs(0, -1)
  # echo dp
  var ans = newSeq[int](n)
  var q = initDeque[(int, int, int, int)]()
  q.addLast((0, -1, 0, 0))
  while q.len > 0:
    let (i, p, a, b) = q.popFirst
    var tot = 0
    for e in g[i]:
      if e.to == p:
        tot += b + a * e.cost
      else:
        tot += dp[e.to] + size[e.to] * e.cost
    ans[i] = tot
    for e in g[i]:
      if e.to != p:
        let
          na = a + size[i] - size[e.to]
          nb = tot - dp[e.to] - size[e.to] * e.cost
        q.addLast((e.to, i, na, nb))
  echo ans.sum
main()
0