結果

問題 No.1094 木登り / Climbing tree
ユーザー takakintakakin
提出日時 2020-07-25 21:25:47
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,304 bytes
コンパイル時間 172 ms
コンパイル使用メモリ 10,876 KB
実行使用メモリ 13,520 KB
最終ジャッジ日時 2023-09-09 23:47:45
合計ジャッジ時間 9,134 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 15 ms
13,520 KB
testcase_01 TLE -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input=lambda: sys.stdin.readline().rstrip()
n=int(input())

Edge=[[] for i in range(n)]
for i in range(n-1):
  a,b,c=map(int,input().split())
  Edge[a-1].append((c,b-1))
  Edge[b-1].append((c,a-1))

inf=float("inf")

prv=[inf]*n #各頂点の親
prv[0]=-1
depth=[inf]*n #深さ
depth[0]=0
stack=[0]
while stack:
  cur=stack.pop()
  for w,next in Edge[cur]:
    if prv[next]==inf:
      prv[next]=cur
      depth[next]=depth[cur]+1
      stack.append(next)

#LCA
LV=(n-1).bit_length() #n=頂点数
def construct(prv):
  kprv=[prv]
  S=prv
  for k in range(LV):
    T=[0]*n
    for i in range(n):
      if S[i] is None:
        continue
      T[i]=S[S[i]]
    kprv.append(T)
    S=T
  return kprv
kprv=construct(prv) # kprv[k][u]=v: 頂点uの2^k個上の祖先頂点v

def lca(u,v,kprv,depth):
  dd=depth[v]-depth[u]
  if dd<0:
    u,v=v,u
    dd=-dd

  for k in range(LV+1):
    if dd&1:
      v=kprv[k][v]
    dd>>=1

  if u==v:
    return u

  for k in range(LV-1,-1,-1):
    pu,pv=kprv[k][u],kprv[k][v]
    if pu!=pv:
      u,v=pu,pv

  return kprv[0][u]

D=[inf]*n
D[0]=0
S=[0]
while S:
	next=S.pop()
	for w,g in Edge[next]:
		if D[g]==inf:
			D[g]=D[next]+w
			S.append(g)

q=int(input())
for _ in range(q):
	s,t=map(int,input().split())
	print(D[s-1]+D[t-1]-2*D[lca(s-1,t-1,kprv,depth)])
0