結果

問題 No.1094 木登り / Climbing tree
ユーザー ああいいああいい
提出日時 2021-12-23 23:32:31
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,827 ms / 2,000 ms
コード長 1,132 bytes
コンパイル時間 694 ms
コンパイル使用メモリ 81,148 KB
実行使用メモリ 141,384 KB
最終ジャッジ日時 2023-10-18 23:10:28
合計ジャッジ時間 37,675 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 45 ms
53,392 KB
testcase_01 AC 1,827 ms
140,216 KB
testcase_02 AC 301 ms
138,260 KB
testcase_03 AC 502 ms
80,332 KB
testcase_04 AC 545 ms
103,980 KB
testcase_05 AC 712 ms
132,008 KB
testcase_06 AC 972 ms
95,872 KB
testcase_07 AC 1,609 ms
141,032 KB
testcase_08 AC 1,624 ms
141,032 KB
testcase_09 AC 1,587 ms
141,032 KB
testcase_10 AC 1,611 ms
141,032 KB
testcase_11 AC 1,602 ms
141,372 KB
testcase_12 AC 1,590 ms
141,360 KB
testcase_13 AC 1,623 ms
141,384 KB
testcase_14 AC 1,602 ms
141,312 KB
testcase_15 AC 873 ms
90,440 KB
testcase_16 AC 1,103 ms
124,824 KB
testcase_17 AC 966 ms
105,556 KB
testcase_18 AC 929 ms
97,760 KB
testcase_19 AC 1,023 ms
115,932 KB
testcase_20 AC 1,616 ms
141,376 KB
testcase_21 AC 999 ms
106,968 KB
testcase_22 AC 1,604 ms
140,768 KB
testcase_23 AC 1,586 ms
140,300 KB
testcase_24 AC 1,576 ms
140,240 KB
testcase_25 AC 1,794 ms
140,256 KB
testcase_26 AC 1,575 ms
140,288 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

N = int(input())
G = [[] for _ in range(N+1)]
for _ in range(N-1):
    a,b,c = map(int,input().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(input())
for _ in range(Q):
    s,t = map(int,input().split())
    l = lca(s,t)
    ans = depth[s] + depth[t] - 2 * depth[l]
    print(ans)

    
0