結果
問題 | No.386 貪欲な領主 |
ユーザー | qib |
提出日時 | 2022-10-15 20:05:43 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 744 ms / 2,000 ms |
コード長 | 1,304 bytes |
コンパイル時間 | 216 ms |
コンパイル使用メモリ | 82,476 KB |
実行使用メモリ | 109,336 KB |
最終ジャッジ日時 | 2024-06-26 20:16:30 |
合計ジャッジ時間 | 5,945 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 44 ms
55,692 KB |
testcase_01 | AC | 41 ms
54,516 KB |
testcase_02 | AC | 42 ms
54,916 KB |
testcase_03 | AC | 43 ms
55,400 KB |
testcase_04 | AC | 744 ms
108,092 KB |
testcase_05 | AC | 589 ms
109,336 KB |
testcase_06 | AC | 626 ms
108,788 KB |
testcase_07 | AC | 102 ms
77,428 KB |
testcase_08 | AC | 187 ms
81,072 KB |
testcase_09 | AC | 119 ms
77,808 KB |
testcase_10 | AC | 41 ms
54,832 KB |
testcase_11 | AC | 42 ms
55,284 KB |
testcase_12 | AC | 94 ms
77,576 KB |
testcase_13 | AC | 147 ms
78,832 KB |
testcase_14 | AC | 623 ms
108,832 KB |
testcase_15 | AC | 636 ms
108,092 KB |
ソースコード
from collections import deque n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) g[a].append(b) g[b].append(a) u = [int(input()) for _ in range(n)] src = 0 depth = [None for _ in range(n)] depth[src] = 0 dq = deque() dq.appendleft(src) k = n.bit_length() doub = [[None for _ in range(n)] for _ in range(k)] doub[0][src] = src cost = [0 for _ in range(n)] cost[src] = u[src] while len(dq) > 0: cur = dq.pop() for nxt in g[cur]: if not depth[nxt] is None: continue depth[nxt] = depth[cur] + 1 cost[nxt] = cost[cur] + u[nxt] doub[0][nxt] = cur dq.appendleft(nxt) for i in range(1, k): for v in range(n): doub[i][v] = doub[i - 1][doub[i - 1][v]] def lca(u, v): ut = u vt = v if depth[ut] > depth[vt]: ut, vt = vt, ut diff = depth[vt] - depth[ut] for i in range(k): if (diff >> i) & 1 != 0: vt = doub[i][vt] if ut != vt: for i in range(depth[ut].bit_length() - 1, -1, -1): if doub[i][ut] != doub[i][vt]: ut = doub[i][ut] vt = doub[i][vt] if ut != vt: ut = doub[0][ut] return ut ans = 0 m = int(input()) for _ in range(m): a, b, c = map(int, input().split()) l = lca(a, b) ans += c * (cost[a] + cost[b] - 2 * cost[l] + u[l]) print(ans)