結果

問題 No.1094 木登り / Climbing tree
ユーザー 👑 KazunKazun
提出日時 2020-07-03 03:09:14
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,110 bytes
コンパイル時間 700 ms
コンパイル使用メモリ 86,880 KB
実行使用メモリ 163,600 KB
最終ジャッジ日時 2023-10-14 03:56:47
合計ジャッジ時間 58,358 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 97 ms
71,608 KB
testcase_01 TLE -
testcase_02 AC 537 ms
153,192 KB
testcase_03 AC 644 ms
84,632 KB
testcase_04 AC 776 ms
116,720 KB
testcase_05 AC 1,207 ms
151,312 KB
testcase_06 AC 1,310 ms
107,244 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,213 ms
98,032 KB
testcase_16 AC 1,755 ms
141,220 KB
testcase_17 AC 1,540 ms
116,192 KB
testcase_18 AC 1,416 ms
107,080 KB
testcase_19 AC 1,660 ms
130,172 KB
testcase_20 TLE -
testcase_21 AC 1,598 ms
118,764 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(w*N+v-1)
    E[v].append(w*N+u-1)

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 x in E[v]:
        u=x%N+1
        w=x//N
        
        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