結果

問題 No.898 tri-βutree
ユーザー 👑 H20H20
提出日時 2021-10-01 13:21:11
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,648 ms / 4,000 ms
コード長 1,477 bytes
コンパイル時間 2,210 ms
コンパイル使用メモリ 86,500 KB
実行使用メモリ 214,192 KB
最終ジャッジ日時 2023-09-26 04:36:02
合計ジャッジ時間 31,843 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1,091 ms
214,192 KB
testcase_01 AC 76 ms
71,244 KB
testcase_02 AC 85 ms
75,904 KB
testcase_03 AC 86 ms
75,884 KB
testcase_04 AC 84 ms
75,912 KB
testcase_05 AC 82 ms
75,684 KB
testcase_06 AC 83 ms
75,884 KB
testcase_07 AC 1,571 ms
112,184 KB
testcase_08 AC 1,648 ms
112,740 KB
testcase_09 AC 1,597 ms
113,328 KB
testcase_10 AC 1,604 ms
113,748 KB
testcase_11 AC 1,572 ms
114,640 KB
testcase_12 AC 1,561 ms
113,728 KB
testcase_13 AC 1,553 ms
113,684 KB
testcase_14 AC 1,596 ms
112,876 KB
testcase_15 AC 1,632 ms
113,284 KB
testcase_16 AC 1,611 ms
114,600 KB
testcase_17 AC 1,561 ms
112,700 KB
testcase_18 AC 1,636 ms
113,968 KB
testcase_19 AC 1,606 ms
112,072 KB
testcase_20 AC 1,624 ms
113,436 KB
testcase_21 AC 1,617 ms
113,724 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(10**6)

# N: 頂点数
# G[v]: 頂点vの子頂点 (親頂点は含む)

# Euler Tour の構築
N = int(input())
G = [[] for _ in range(N)]

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

S = []
F = [0]*N
depth = [0]*N

def dfs(v, d , p):
    F[v] = len(S)
    depth[v] = d
    S.append(v)
    for n,w in G[v]:
        if p!=n:
            dfs(n, d+w, v)
            S.append(v)
dfs(0, 0, -1)

# 存在しない範囲は深さが他よりも大きくなるようにする
INF = (10**18, 0)

# LCAを計算するクエリの前計算
M = 2*N
M0 = 2**(M-1).bit_length()
data = [INF]*(2*M0)
for i, v in enumerate(S):
    data[M0-1+i] = (depth[v], i)
for i in range(M0-2, -1, -1):
    data[i] = min(data[2*i+1], data[2*i+2])

# LCAの計算 (generatorで最小値を求める)
def _query(a, b):
    yield INF
    a += M0; b += M0
    while a < b:
        if b & 1:
            b -= 1
            yield data[b-1]
        if a & 1:
            yield data[a-1]
            a += 1
        a >>= 1; b >>= 1

# LCAの計算 (外から呼び出す関数)
def query(u, v):
    fu = F[u]; fv = F[v]
    if fu > fv:
        fu, fv = fv, fu
    return S[min(_query(fu, fv+1))[1]]

# 2点間の距離
def distance(u, v):
    return depth[u]+depth[v]-2*depth[query(u, v)]

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