結果
問題 | No.898 tri-βutree |
ユーザー | ttr |
提出日時 | 2020-02-24 14:16:27 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 2,224 ms / 4,000 ms |
コード長 | 1,896 bytes |
コンパイル時間 | 475 ms |
コンパイル使用メモリ | 81,920 KB |
実行使用メモリ | 131,556 KB |
最終ジャッジ日時 | 2024-11-08 23:28:54 |
合計ジャッジ時間 | 35,532 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 311 ms
117,888 KB |
testcase_01 | AC | 48 ms
54,144 KB |
testcase_02 | AC | 59 ms
62,592 KB |
testcase_03 | AC | 61 ms
62,720 KB |
testcase_04 | AC | 60 ms
62,848 KB |
testcase_05 | AC | 60 ms
62,720 KB |
testcase_06 | AC | 60 ms
62,336 KB |
testcase_07 | AC | 2,127 ms
130,928 KB |
testcase_08 | AC | 2,132 ms
130,820 KB |
testcase_09 | AC | 2,170 ms
129,264 KB |
testcase_10 | AC | 2,089 ms
129,072 KB |
testcase_11 | AC | 2,166 ms
129,732 KB |
testcase_12 | AC | 2,120 ms
128,280 KB |
testcase_13 | AC | 2,033 ms
127,936 KB |
testcase_14 | AC | 2,224 ms
129,948 KB |
testcase_15 | AC | 2,150 ms
127,884 KB |
testcase_16 | AC | 2,024 ms
127,728 KB |
testcase_17 | AC | 2,063 ms
129,360 KB |
testcase_18 | AC | 2,143 ms
128,692 KB |
testcase_19 | AC | 2,107 ms
128,840 KB |
testcase_20 | AC | 2,183 ms
130,672 KB |
testcase_21 | AC | 2,207 ms
131,556 KB |
ソースコード
import sys input = sys.stdin.buffer.readline N = int(input()) E = [[]for _ in range(N)] for _ in range(N-1): u,v,w = map(int, input().split()) E[u].append((v, w)) E[v].append((u, w)) from collections import deque inf = 10**15 dist = [inf]*N dist[0] = 0 q = deque() q.append((0, 0)) while q: temp = q.popleft() u = temp[0] d = temp[1] for l in E[u]: if dist[l[0]] < inf: continue dist[l[0]] = d+l[1] q.append((l[0], d+l[1])) #LCA par = [-1]*N rnk = [-1]*N par[0] = 0 rnk[0] = 0 q = deque() q.append((0, 0)) while q: temp = q.popleft() v = temp[0] r = temp[1] for l in E[v]: if par[l[0]] < 0: par[l[0]] = v rnk[l[0]] = r+1 q.append((l[0], r+1)) par[0] = 0 LV = (N-1).bit_length() kpar = [par] for k in range(LV): T = [0]*N for i in range(N): if par[i] == 0: continue T[i] = par[par[i]] kpar.append(T) par = T def lca(u, v): if rnk[u] > rnk[v]: u, v = v, u d = rnk[v]-rnk[u] for i in range(LV+1): if d&1: v = kpar[i][v] d >>= 1 if u == v: return u for k in range(LV-1, -1, -1): pu = kpar[k][u] pv = kpar[k][v] if pu != pv: u = pu v = pv return kpar[0][u] Q = int(input()) for _ in range(Q): x,y,z = map(int, input().split()) a = lca(x, y) b = lca(y, z) c = lca(z, x) if rnk[a] >= rnk[b] and rnk[a] >= rnk[c]: ans = dist[x]+dist[y]-2*dist[a] d = lca(a, z) ans += dist[a]+dist[z]-2*dist[d] elif rnk[b] >= rnk[c] and rnk[b] >= rnk[a]: ans = dist[y]+dist[z]-2*dist[b] d = lca(b, x) ans += dist[b]+dist[x]-2*dist[d] else: ans = dist[z]+dist[x]-2*dist[c] d = lca(c, y) ans += dist[c]+dist[y]-2*dist[d] print(ans)