結果

問題 No.386 貪欲な領主
ユーザー qibqib
提出日時 2022-10-15 20:05:43
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 728 ms / 2,000 ms
コード長 1,304 bytes
コンパイル時間 374 ms
コンパイル使用メモリ 87,028 KB
実行使用メモリ 110,836 KB
最終ジャッジ日時 2023-09-09 03:04:14
合計ジャッジ時間 7,550 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 94 ms
71,496 KB
testcase_01 AC 92 ms
71,692 KB
testcase_02 AC 93 ms
71,496 KB
testcase_03 AC 92 ms
71,320 KB
testcase_04 AC 728 ms
110,784 KB
testcase_05 AC 607 ms
110,728 KB
testcase_06 AC 626 ms
110,276 KB
testcase_07 AC 156 ms
78,244 KB
testcase_08 AC 239 ms
83,236 KB
testcase_09 AC 173 ms
79,380 KB
testcase_10 AC 91 ms
71,772 KB
testcase_11 AC 90 ms
71,468 KB
testcase_12 AC 140 ms
78,296 KB
testcase_13 AC 191 ms
80,336 KB
testcase_14 AC 621 ms
110,480 KB
testcase_15 AC 673 ms
110,836 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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)
0