結果
問題 | No.898 tri-βutree |
ユーザー | ttr |
提出日時 | 2020-02-24 14:13:50 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 2,593 ms / 4,000 ms |
コード長 | 1,851 bytes |
コンパイル時間 | 368 ms |
コンパイル使用メモリ | 82,176 KB |
実行使用メモリ | 131,328 KB |
最終ジャッジ日時 | 2024-11-08 23:28:07 |
合計ジャッジ時間 | 39,694 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 557 ms
114,668 KB |
testcase_01 | AC | 47 ms
54,272 KB |
testcase_02 | AC | 60 ms
62,976 KB |
testcase_03 | AC | 61 ms
63,488 KB |
testcase_04 | AC | 61 ms
63,744 KB |
testcase_05 | AC | 60 ms
62,848 KB |
testcase_06 | AC | 61 ms
62,976 KB |
testcase_07 | AC | 2,409 ms
129,276 KB |
testcase_08 | AC | 2,341 ms
126,848 KB |
testcase_09 | AC | 2,387 ms
129,652 KB |
testcase_10 | AC | 2,296 ms
126,972 KB |
testcase_11 | AC | 2,382 ms
127,088 KB |
testcase_12 | AC | 2,295 ms
127,312 KB |
testcase_13 | AC | 2,282 ms
127,160 KB |
testcase_14 | AC | 2,435 ms
128,004 KB |
testcase_15 | AC | 2,420 ms
129,244 KB |
testcase_16 | AC | 2,267 ms
127,040 KB |
testcase_17 | AC | 2,110 ms
126,144 KB |
testcase_18 | AC | 2,435 ms
127,992 KB |
testcase_19 | AC | 2,445 ms
128,784 KB |
testcase_20 | AC | 2,356 ms
128,268 KB |
testcase_21 | AC | 2,593 ms
131,328 KB |
ソースコード
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)