結果

問題 No.1094 木登り / Climbing tree
ユーザー rlangevinrlangevin
提出日時 2023-02-04 15:01:26
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,357 ms / 2,000 ms
コード長 1,489 bytes
コンパイル時間 962 ms
コンパイル使用メモリ 86,704 KB
実行使用メモリ 171,784 KB
最終ジャッジ日時 2023-09-16 11:42:54
合計ジャッジ時間 29,838 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 88 ms
71,756 KB
testcase_01 AC 1,315 ms
171,784 KB
testcase_02 AC 307 ms
168,988 KB
testcase_03 AC 272 ms
83,012 KB
testcase_04 AC 416 ms
118,736 KB
testcase_05 AC 589 ms
157,572 KB
testcase_06 AC 629 ms
107,200 KB
testcase_07 AC 1,231 ms
171,568 KB
testcase_08 AC 1,175 ms
169,688 KB
testcase_09 AC 1,161 ms
169,236 KB
testcase_10 AC 1,177 ms
169,912 KB
testcase_11 AC 1,187 ms
170,212 KB
testcase_12 AC 1,179 ms
169,468 KB
testcase_13 AC 1,193 ms
169,748 KB
testcase_14 AC 1,176 ms
170,068 KB
testcase_15 AC 358 ms
98,644 KB
testcase_16 AC 587 ms
147,008 KB
testcase_17 AC 500 ms
119,076 KB
testcase_18 AC 448 ms
108,880 KB
testcase_19 AC 576 ms
136,068 KB
testcase_20 AC 1,193 ms
169,616 KB
testcase_21 AC 513 ms
122,160 KB
testcase_22 AC 1,223 ms
170,184 KB
testcase_23 AC 1,189 ms
171,348 KB
testcase_24 AC 1,166 ms
171,020 KB
testcase_25 AC 1,357 ms
171,284 KB
testcase_26 AC 1,174 ms
171,276 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
readline = sys.stdin.readline
from collections import deque

def f(G, s, N):
    Q = deque([])
    dist = [-1] * N
    par = [-1] * N
    depth = [0] * N
    dist[s] = 0
    for u, c in G[s]:
        par[u] = s
        dist[u] = c
        depth[u] = 1
        Q.append(u)

    while Q:
        u = Q.popleft()
        for v, c in G[u]:
            if dist[v] != -1:
                continue
            dist[v] = dist[u] + c
            depth[v] = depth[u] + 1
            par[v] = u
            Q.append(v)
            
    return dist, par, depth

def doubling(X):
    M = 35
    dp = [[0] * len(X) for i in range(M)]
    dp[0] = X
    for i in range(M - 1):
        for j in range(len(X)):
            dp[i + 1][j] = dp[i][dp[i][j]]
    return dp
        


N = int(readline())
G = [[] for i in range(N)]
for i in range(N - 1):
    a, b, c = map(int, readline().split())
    a, b = a - 1 ,b - 1
    G[a].append((b, c))
    G[b].append((a, c))
    
D, P, DD = f(G, 0, N)
dp = doubling(P)

Q = int(readline())
for _ in range(Q):
    s, t = map(int, readline().split())
    s, t = s - 1, t - 1
    ps, pt = s, t
    if DD[s] > DD[t]:
        s, t = t, s
    d = DD[t] - DD[s]
    for i in range(30):
        if (d >> i) & 1:
            t = dp[i][t]
    if s == t:
        LCA = s
    else:
        for i in range(30, -1, -1):
            if dp[i][s] != dp[i][t]:
                s = dp[i][s]
                t = dp[i][t]
        LCA = P[s]
    print(D[ps] + D[pt] - 2 * D[LCA])
0