結果

問題 No.1094 木登り / Climbing tree
ユーザー 👑 KazunKazun
提出日時 2021-01-05 00:05:47
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,106 ms / 2,000 ms
コード長 1,102 bytes
コンパイル時間 452 ms
コンパイル使用メモリ 82,504 KB
実行使用メモリ 147,320 KB
最終ジャッジ日時 2024-04-25 19:35:00
合計ジャッジ時間 23,447 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 36 ms
54,712 KB
testcase_01 AC 1,061 ms
147,320 KB
testcase_02 AC 245 ms
138,680 KB
testcase_03 AC 270 ms
82,672 KB
testcase_04 AC 338 ms
108,312 KB
testcase_05 AC 560 ms
136,872 KB
testcase_06 AC 553 ms
100,184 KB
testcase_07 AC 1,069 ms
146,560 KB
testcase_08 AC 1,067 ms
146,416 KB
testcase_09 AC 929 ms
146,680 KB
testcase_10 AC 945 ms
146,152 KB
testcase_11 AC 1,059 ms
146,428 KB
testcase_12 AC 1,048 ms
146,408 KB
testcase_13 AC 940 ms
146,284 KB
testcase_14 AC 913 ms
146,528 KB
testcase_15 AC 311 ms
93,312 KB
testcase_16 AC 580 ms
127,324 KB
testcase_17 AC 466 ms
108,384 KB
testcase_18 AC 396 ms
101,192 KB
testcase_19 AC 499 ms
119,472 KB
testcase_20 AC 1,060 ms
146,268 KB
testcase_21 AC 457 ms
109,904 KB
testcase_22 AC 945 ms
146,324 KB
testcase_23 AC 957 ms
147,096 KB
testcase_24 AC 1,106 ms
147,072 KB
testcase_25 AC 1,047 ms
147,060 KB
testcase_26 AC 1,071 ms
146,836 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque
import sys
input=sys.stdin.readline

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]*(N+1) for _ in range(J)]
Depth=[None]*(N+1)

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


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[0][u]=v
            Q.append(u)

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

def upper(u,k):
    i=0
    while k>0:
        if k%2==1:
            u=A[i][u]
        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):
        X=A[j]
        if X[u]!=X[v]:
            u=X[u]
            v=X[v]

    return A[0][u]

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