結果

問題 No.898 tri-βutree
ユーザー H3PO4H3PO4
提出日時 2021-03-27 09:00:44
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 998 ms / 4,000 ms
コード長 1,935 bytes
コンパイル時間 263 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 120,064 KB
最終ジャッジ日時 2024-04-26 09:35:54
合計ジャッジ時間 17,669 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 285 ms
120,064 KB
testcase_01 AC 46 ms
54,144 KB
testcase_02 AC 56 ms
61,824 KB
testcase_03 AC 55 ms
61,952 KB
testcase_04 AC 57 ms
61,696 KB
testcase_05 AC 55 ms
61,824 KB
testcase_06 AC 55 ms
61,824 KB
testcase_07 AC 955 ms
117,332 KB
testcase_08 AC 944 ms
116,600 KB
testcase_09 AC 935 ms
115,688 KB
testcase_10 AC 954 ms
115,932 KB
testcase_11 AC 968 ms
116,680 KB
testcase_12 AC 947 ms
116,512 KB
testcase_13 AC 957 ms
115,764 KB
testcase_14 AC 974 ms
116,320 KB
testcase_15 AC 962 ms
116,564 KB
testcase_16 AC 984 ms
116,304 KB
testcase_17 AC 981 ms
115,836 KB
testcase_18 AC 969 ms
117,300 KB
testcase_19 AC 979 ms
116,376 KB
testcase_20 AC 972 ms
115,628 KB
testcase_21 AC 998 ms
117,116 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

input = sys.stdin.buffer.readline

N = int(input())
T = [[] for _ in range(N)]
for _ in range(N - 1):
    u, v, w = map(int, input().split())
    T[u].append((v, w))
    T[v].append((u, w))

d = deque([0])
prv = [-1] * N
depth = [None] * N
depth[0] = 0
acc = [0] * N
while d:
    v = d.pop()
    depv = depth[v]
    accv = acc[v]
    for x, w in T[v]:
        if depth[x] is None:
            prv[x] = v
            depth[x] = depv + 1
            acc[x] = accv + w
            d.append(x)

# https://tjkendev.github.io/procon-library/python/graph/lca-doubling.html から拝借しています。

# N: 頂点数
# G[v]: 頂点vの子頂点 (親頂点は含まない)
#
# - construct
# prv[u] = v: 頂点uの一つ上の祖先頂点v
# - lca
# kprv[k][u] = v: 頂点uの2^k個上の祖先頂点v
# depth[u]: 頂点uの深さ (根頂点は0)

LV = (N - 1).bit_length()


def construct(prv):
    kprv = [prv]
    S = prv
    for k in range(LV):
        T = [0] * N
        for i in range(N):
            if S[i] is None:
                continue
            T[i] = S[S[i]]
        kprv.append(T)
        S = T
    return kprv


def lca(u, v, kprv, depth):
    dd = depth[v] - depth[u]
    if dd < 0:
        u, v = v, u
        dd = -dd

    # assert depth[u] <= depth[v]
    for k in range(LV + 1):
        if dd & 1:
            v = kprv[k][v]
        dd >>= 1

    # assert depth[u] == depth[v]
    if u == v:
        return u

    for k in range(LV - 1, -1, -1):
        pu = kprv[k][u]
        pv = kprv[k][v]
        if pu != pv:
            u = pu
            v = pv

    # assert kprv[0][u] == kprv[0][v]
    return kprv[0][u]


kprv = construct(prv)


def dist(u, v):
    l = lca(u, v, kprv, depth)
    return acc[u] + acc[v] - 2 * acc[l]


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