結果
| 問題 | 
                            No.1094 木登り / Climbing tree
                             | 
                    
| ユーザー | 
                            👑  Kazun
                         | 
                    
| 提出日時 | 2020-06-26 00:36:22 | 
| 言語 | PyPy3  (7.3.15)  | 
                    
| 結果 | 
                             
                                TLE
                                 
                             
                            
                         | 
                    
| 実行時間 | - | 
| コード長 | 1,086 bytes | 
| コンパイル時間 | 155 ms | 
| コンパイル使用メモリ | 82,280 KB | 
| 実行使用メモリ | 203,388 KB | 
| 最終ジャッジ日時 | 2024-09-14 22:19:00 | 
| 合計ジャッジ時間 | 7,765 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge6 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 1 | 
| other | TLE * 1 -- * 25 | 
ソースコード
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={i:None for i in range(1,N+1)}
A=[[1]*J for _ in range(N+1)]
Depth={i:None for i in range(1,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):
    x=Depth[u]
    y=Depth[v]
    u=upper(u,max(x-y,0))
    v=upper(v,max(y-x,0))
    P=2**(J-1)
    while P>0:
        if upper(u,P)!=upper(v,P):
            u=upper(u,P)
            v=upper(v,P)
        P//=2
    return upper(u,1)
        
    
Q=int(input())
for _ in range(Q):
    u,v=map(int,input().split())
    print(T[u]+T[v]-2*T[lca(u,v)])
            
            
            
        
            
Kazun