結果

問題 No.898 tri-βutree
ユーザー lloyzlloyz
提出日時 2022-02-23 22:45:57
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,001 ms / 4,000 ms
コード長 1,781 bytes
コンパイル時間 355 ms
コンパイル使用メモリ 87,220 KB
実行使用メモリ 220,548 KB
最終ジャッジ日時 2023-09-14 16:03:39
合計ジャッジ時間 35,090 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 766 ms
220,548 KB
testcase_01 AC 92 ms
71,556 KB
testcase_02 AC 107 ms
77,348 KB
testcase_03 AC 107 ms
77,496 KB
testcase_04 AC 105 ms
77,680 KB
testcase_05 AC 105 ms
77,248 KB
testcase_06 AC 106 ms
77,516 KB
testcase_07 AC 1,602 ms
132,268 KB
testcase_08 AC 1,574 ms
132,744 KB
testcase_09 AC 1,562 ms
131,500 KB
testcase_10 AC 1,944 ms
131,120 KB
testcase_11 AC 1,571 ms
131,156 KB
testcase_12 AC 1,972 ms
132,300 KB
testcase_13 AC 1,948 ms
132,504 KB
testcase_14 AC 1,967 ms
131,652 KB
testcase_15 AC 1,970 ms
132,900 KB
testcase_16 AC 1,653 ms
135,620 KB
testcase_17 AC 1,574 ms
132,424 KB
testcase_18 AC 2,001 ms
132,044 KB
testcase_19 AC 1,984 ms
131,936 KB
testcase_20 AC 1,948 ms
132,284 KB
testcase_21 AC 1,996 ms
133,412 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict, deque
import sys
sys.setrecursionlimit(10**6)

n = int(input())

max_log_v = 30

# 親を2^k回辿って到達する頂点(根を通り過ぎる場合は-1とする)
Parent = [[-1 for _ in range(n)] for _ in range(max_log_v)]
Depth = [-1 for _ in range(n)]
def dfs(curr, prev, d):
    Parent[0][curr] = prev
    Depth[curr] = d
    for np, _ in edge[curr]:
        if np == prev:
            continue
        dfs(np, curr, d + 1)

def init():
    root = 0
    # Parent[0]とDepthを根rootの木として初期化する
    dfs(root, -1, 0)
    # Parentを初期化する
    for i in range(max_log_v - 1):
        for v in range(n):
            if Parent[i][v] < 0:
                Parent[i + 1][v] = -1
            else:
                Parent[i + 1][v] = Parent[i][Parent[i][v]]

def check_LCA(u, v):
    if Depth[u] > Depth[v]:
        u, v = v, u
    for i in range(max_log_v):
        if (Depth[v] - Depth[u]) >> i & 1:
            v = Parent[i][v]
    if u == v:
        return u
    for i in range(max_log_v - 1, -1, -1):
        if Parent[i][u] != Parent[i][v]:
            u = Parent[i][u]
            v = Parent[i][v]
    return Parent[0][u]

edge = defaultdict(list)
for _ in range(n - 1):
    u, v, w = map(int, input().split())
    edge[u].append((v, w))
    edge[v].append((u, w))

init()

INF = 1 << 60
D = [INF for _ in range(n)]
D[0] = 0
Que = deque([(0, 0)])
while Que:
    curr, d = Que.popleft()
    for np, w in edge[curr]:
        if d + w > D[np]:
            continue
        D[np] = d + w
        Que.append((np, d + w))

def dist(u, v):
    return D[u] + D[v] - 2 * D[check_LCA(u, v)]

q = int(input())
for _ in range(q):
    x, y, z = map(int, input().split())
    print((dist(x, y) + dist(y, z) + dist(z, x)) // 2)
0