結果
問題 |
No.1094 木登り / Climbing tree
|
ユーザー |
![]() |
提出日時 | 2021-01-13 06:31:28 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,311 ms / 2,000 ms |
コード長 | 2,054 bytes |
コンパイル時間 | 554 ms |
コンパイル使用メモリ | 82,560 KB |
実行使用メモリ | 146,044 KB |
最終ジャッジ日時 | 2024-11-08 07:16:01 |
合計ジャッジ時間 | 27,272 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 26 |
ソースコード
import sys from collections import deque sys.setrecursionlimit(10**7) def I(): return int(sys.stdin.readline().rstrip()) def MI(): return map(int,sys.stdin.readline().rstrip().split()) def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) def LI2(): return list(map(int,sys.stdin.readline().rstrip())) def S(): return sys.stdin.readline().rstrip() def LS(): return list(sys.stdin.readline().rstrip().split()) def LS2(): return list(sys.stdin.readline().rstrip()) N = I() Graph = [[] for _ in range(N)] # 0-index for _ in range(N-1): a,b,c = MI() a -= 1 b -= 1 Graph[a].append((b,c)) Graph[b].append((a,c)) # 0を頂点とした根付き木 depth = [-1]*N parent = [-1]*N dist = [-1]*N # 根からの距離 depth[0] = 0 dist[0] = 0 deq = deque([(0,-1)]) while deq: i,p = deq.pop() for j,c in Graph[i]: if j == p: continue depth[j] = depth[i]+1 parent[j] = i dist[j] = dist[i]+c deq.appendleft((j,i)) K = (N-1).bit_length()+1 ancestor = [[-1]*N for k in range(K)] # parents[k][x] = 頂点xの2**k世代先祖 for k in range(K): if k == 0: ancestor[k] = parent else: for x in range(N): if ancestor[k-1][x] == -1: ancestor[k][x] = -1 else: ancestor[k][x] = ancestor[k-1][ancestor[k-1][x]] def lca(x,y): # xとyの最近共通祖先 depth_difference = depth[x] - depth[y] if depth_difference < 0: x,y = y,x depth_difference = -depth_difference # depth[x] >= depth[y] としてよい for k in range(K): if depth_difference & 1: x = ancestor[k][x] depth_difference >>= 1 # depth[x] == depth[y] としてよい if x == y: return x for k in range(K-1,-1,-1): px,py = ancestor[k][x],ancestor[k][y] if px != py: x,y = px,py return ancestor[0][x] Q = I() for _ in range(Q): s,t = MI() s -= 1 t -= 1 a = lca(s,t) print(dist[s]+dist[t]-2*dist[a])