結果
問題 | No.898 tri-βutree |
ユーザー | ttr |
提出日時 | 2020-02-24 14:16:05 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
AC
|
実行時間 | 3,089 ms / 4,000 ms |
コード長 | 1,896 bytes |
コンパイル時間 | 253 ms |
コンパイル使用メモリ | 12,800 KB |
実行使用メモリ | 64,640 KB |
最終ジャッジ日時 | 2024-10-12 04:13:39 |
合計ジャッジ時間 | 51,912 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 1,766 ms
61,824 KB |
testcase_01 | AC | 28 ms
11,008 KB |
testcase_02 | AC | 29 ms
11,136 KB |
testcase_03 | AC | 28 ms
11,136 KB |
testcase_04 | AC | 28 ms
10,880 KB |
testcase_05 | AC | 29 ms
11,008 KB |
testcase_06 | AC | 29 ms
11,136 KB |
testcase_07 | AC | 2,922 ms
64,512 KB |
testcase_08 | AC | 2,965 ms
64,384 KB |
testcase_09 | AC | 2,997 ms
64,640 KB |
testcase_10 | AC | 2,963 ms
64,512 KB |
testcase_11 | AC | 2,983 ms
64,640 KB |
testcase_12 | AC | 3,089 ms
64,256 KB |
testcase_13 | AC | 2,965 ms
64,512 KB |
testcase_14 | AC | 3,037 ms
64,512 KB |
testcase_15 | AC | 2,966 ms
64,640 KB |
testcase_16 | AC | 2,902 ms
64,640 KB |
testcase_17 | AC | 2,985 ms
64,640 KB |
testcase_18 | AC | 2,999 ms
64,640 KB |
testcase_19 | AC | 2,955 ms
64,512 KB |
testcase_20 | AC | 2,974 ms
64,640 KB |
testcase_21 | AC | 2,990 ms
64,512 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)