結果

問題 No.1094 木登り / Climbing tree
ユーザー 👑 KazunKazun
提出日時 2020-07-02 16:35:18
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,056 bytes
コンパイル時間 1,560 ms
コンパイル使用メモリ 87,232 KB
実行使用メモリ 172,020 KB
最終ジャッジ日時 2023-10-13 03:26:35
合計ジャッジ時間 54,884 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 99 ms
71,668 KB
testcase_01 TLE -
testcase_02 AC 526 ms
158,228 KB
testcase_03 AC 621 ms
85,368 KB
testcase_04 AC 724 ms
120,592 KB
testcase_05 AC 1,111 ms
159,376 KB
testcase_06 AC 1,220 ms
110,176 KB
testcase_07 TLE -
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 TLE -
testcase_12 TLE -
testcase_13 TLE -
testcase_14 TLE -
testcase_15 AC 1,115 ms
100,084 KB
testcase_16 AC 1,561 ms
147,504 KB
testcase_17 AC 1,347 ms
121,044 KB
testcase_18 AC 1,243 ms
111,280 KB
testcase_19 AC 1,517 ms
137,324 KB
testcase_20 TLE -
testcase_21 AC 1,401 ms
123,236 KB
testcase_22 TLE -
testcase_23 TLE -
testcase_24 TLE -
testcase_25 TLE -
testcase_26 TLE -
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
J=19

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

T=[None]*(N+1)
A=[[1]*J for _ in range(N+1)]
Depth=[None]*(N+1)

Q=deque()
T[1]=0
Depth[1]=0

Q.append(1)
while Q:
    v=Q.popleft()
    for (u,w) in E[v]:
        if T[u]==None:
            T[u]=T[v]+w
            Depth[u]=Depth[v]+1
            A[u][0]=v
            Q.append(u)

for p in range(J-1):
    for u in range(1,N+1):
        v=A[u][p]
        A[u][p+1]=A[v][p]

def upper(u,k):
    i=0
    while k>0:
        if k%2==1:
            u=A[u][i]
        i+=1
        k//=2
    return u

def lca(u,v):
    x=Depth[u]
    y=Depth[v]
    u=upper(u,max(x-y,0))
    v=upper(v,max(y-x,0))
    
    if u==v:
        return u
    
    for j in range(J-1,-1,-1):
        if A[u][j]!=A[v][j]:
            u=A[u][j]
            v=A[v][j]
            
    return A[u][0]

Q=int(input())
for _ in range(Q):
    u,v=map(int,input().split())
    print(T[u]+T[v]-2*T[lca(u,v)])
0