結果

問題 No.1094 木登り / Climbing tree
ユーザー ああいいああいい
提出日時 2021-12-23 23:34:16
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,274 ms / 2,000 ms
コード長 1,178 bytes
コンパイル時間 437 ms
コンパイル使用メモリ 82,712 KB
実行使用メモリ 143,332 KB
最終ジャッジ日時 2024-04-25 19:46:29
合計ジャッジ時間 24,454 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 38 ms
52,936 KB
testcase_01 AC 1,274 ms
143,332 KB
testcase_02 AC 245 ms
139,288 KB
testcase_03 AC 241 ms
80,848 KB
testcase_04 AC 362 ms
104,812 KB
testcase_05 AC 533 ms
132,544 KB
testcase_06 AC 533 ms
97,248 KB
testcase_07 AC 1,024 ms
141,672 KB
testcase_08 AC 998 ms
141,548 KB
testcase_09 AC 991 ms
141,664 KB
testcase_10 AC 993 ms
141,432 KB
testcase_11 AC 996 ms
141,656 KB
testcase_12 AC 992 ms
141,784 KB
testcase_13 AC 1,025 ms
141,796 KB
testcase_14 AC 1,031 ms
141,900 KB
testcase_15 AC 396 ms
91,128 KB
testcase_16 AC 590 ms
125,940 KB
testcase_17 AC 494 ms
105,588 KB
testcase_18 AC 447 ms
98,776 KB
testcase_19 AC 537 ms
116,964 KB
testcase_20 AC 1,028 ms
141,800 KB
testcase_21 AC 508 ms
107,388 KB
testcase_22 AC 1,019 ms
141,664 KB
testcase_23 AC 985 ms
142,860 KB
testcase_24 AC 997 ms
143,020 KB
testcase_25 AC 1,229 ms
142,776 KB
testcase_26 AC 1,008 ms
142,600 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
r = sys.stdin

N = int(r.readline())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
    a,b,c = map(int,r.readline().split())
    G[a].append((b,c))
    G[b].append((a,c))

n = 1
while 1 << n < N:
    n += 1
dp = [[0] * (N+1) for _ in range(n)]
depth = [0] * (N+1)
depth2 = [0] * (N+1)
q = []
q.append((1,0))
while len(q):
    now,parent = q.pop()
    for v,c in G[now]:
        if v != parent:
            depth[v] = depth[now] + c
            depth2[v] = depth2[now] + 1
            q.append((v,now))
            dp[0][v] = now
for i in range(1,n):
    for j in range(1,N+1):
        dp[i][j] = dp[i-1][dp[i-1][j]]
def lca(u,v):
    if u == v:
        return u
    if depth2[v] > depth2[u]:
        u,v = v,u
    delta = depth2[u] - depth2[v]
    for j in range(n):
        mask = 1 << j
        if delta & mask:
            u = dp[j][u]
    if u == v:return u
    for k in reversed(range(n)):
        if dp[k][u] != dp[k][v]:
            u = dp[k][u]
            v = dp[k][v]
    return dp[0][u]

Q = int(r.readline())
for _ in range(Q):
    s,t = map(int,r.readline().split())
    l = lca(s,t)
    ans = depth[s] + depth[t] - 2 * depth[l]
    print(ans)

    
0