結果

問題 No.1094 木登り / Climbing tree
ユーザー 👑 KazunKazun
提出日時 2020-06-26 00:45:43
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,070 bytes
コンパイル時間 435 ms
コンパイル使用メモリ 86,940 KB
実行使用メモリ 176,064 KB
最終ジャッジ日時 2023-10-13 00:23:51
合計ジャッジ時間 52,012 ms
ジャッジサーバーID
(参考情報)
judge12 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 107 ms
71,636 KB
testcase_01 TLE -
testcase_02 AC 522 ms
157,504 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
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 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 TLE -
testcase_21 WA -
testcase_22 TLE -
testcase_23 TLE -
testcase_24 TLE -
testcase_25 TLE -
testcase_26 TLE -
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
J=18

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(1,J):
    for u in range(1,N+1):
        v=A[u][p-1]
        A[u][p]=A[v][p-1]

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):
    if u==v:
        return u
    
    x=Depth[u]
    y=Depth[v]

    u=upper(u,max(x-y,0))
    v=upper(v,max(y-x,0))

    P=2**(J-1)
    for i in range(J-1,-1,-1):
        if A[u][i]!=A[v][i]:
            u=A[u][i]
            v=A[v][i]
            
    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