結果

問題 No.898 tri-βutree
ユーザー ttrttr
提出日時 2020-02-24 14:13:50
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 2,316 ms / 4,000 ms
コード長 1,851 bytes
コンパイル時間 546 ms
コンパイル使用メモリ 87,184 KB
実行使用メモリ 140,048 KB
最終ジャッジ日時 2023-08-08 16:40:05
合計ジャッジ時間 37,960 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 577 ms
119,992 KB
testcase_01 AC 91 ms
71,524 KB
testcase_02 AC 102 ms
77,044 KB
testcase_03 AC 103 ms
77,096 KB
testcase_04 AC 104 ms
77,052 KB
testcase_05 AC 104 ms
77,144 KB
testcase_06 AC 103 ms
76,944 KB
testcase_07 AC 2,247 ms
136,568 KB
testcase_08 AC 2,206 ms
140,048 KB
testcase_09 AC 2,243 ms
139,140 KB
testcase_10 AC 2,221 ms
136,996 KB
testcase_11 AC 2,277 ms
133,864 KB
testcase_12 AC 2,221 ms
136,724 KB
testcase_13 AC 2,171 ms
136,128 KB
testcase_14 AC 2,293 ms
138,524 KB
testcase_15 AC 2,264 ms
137,740 KB
testcase_16 AC 2,163 ms
135,948 KB
testcase_17 AC 2,194 ms
137,624 KB
testcase_18 AC 2,250 ms
135,600 KB
testcase_19 AC 2,248 ms
139,980 KB
testcase_20 AC 2,263 ms
137,472 KB
testcase_21 AC 2,316 ms
136,176 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

from collections import deque
inf = 10**15
dist = [inf]*N
dist[0] = 0
q = deque()
q.append((0, 0))
while q:
    temp = q.popleft()
    u = temp[0]
    d = temp[1]
    for l in E[u]:
        if dist[l[0]] < inf:
            continue
        dist[l[0]] = d+l[1]
        q.append((l[0], d+l[1]))

#LCA
par = [-1]*N
rnk = [-1]*N
par[0] = 0
rnk[0] = 0
q = deque()
q.append((0, 0))
while q:
    temp = q.popleft()
    v = temp[0]
    r = temp[1]
    for l in E[v]:
        if par[l[0]] < 0:
            par[l[0]] = v
            rnk[l[0]] = r+1
            q.append((l[0], r+1))

par[0] = 0
LV = (N-1).bit_length()
kpar = [par]
for k in range(LV):
    T = [0]*N
    for i in range(N):
        if par[i] == 0:
            continue
        T[i] = par[par[i]]
    kpar.append(T)
    par = T

def lca(u, v):
    if rnk[u] > rnk[v]:
        u, v = v, u
    d = rnk[v]-rnk[u]
    for i in range(LV+1):
        if d&1:
            v = kpar[i][v]
        d >>= 1
    if u == v:
        return u
    for k in range(LV-1, -1, -1):
        pu = kpar[k][u]
        pv = kpar[k][v]
        if pu != pv:
            u = pu
            v = pv
    return kpar[0][u]

Q = int(input())
for _ in range(Q):
    x,y,z = map(int, input().split())
    a = lca(x, y)
    b = lca(y, z)
    c = lca(z, x)
    if rnk[a] >= rnk[b] and rnk[a] >= rnk[c]:
        ans = dist[x]+dist[y]-2*dist[a]
        d = lca(a, z)
        ans += dist[a]+dist[z]-2*dist[d]
    elif rnk[b] >= rnk[c] and rnk[b] >= rnk[a]:
        ans = dist[y]+dist[z]-2*dist[b]
        d = lca(b, x)
        ans += dist[b]+dist[x]-2*dist[d]
    else:
        ans = dist[z]+dist[x]-2*dist[c]
        d = lca(c, y)
        ans += dist[c]+dist[y]-2*dist[d]
    print(ans)
0