結果
問題 | No.898 tri-βutree |
ユーザー | OKCH3COOH |
提出日時 | 2019-10-26 22:11:36 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
WA
|
実行時間 | - |
コード長 | 2,362 bytes |
コンパイル時間 | 536 ms |
コンパイル使用メモリ | 12,800 KB |
実行使用メモリ | 71,552 KB |
最終ジャッジ日時 | 2024-09-14 19:04:43 |
合計ジャッジ時間 | 14,533 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 2,870 ms
68,352 KB |
testcase_01 | AC | 31 ms
10,880 KB |
testcase_02 | WA | - |
testcase_03 | WA | - |
testcase_04 | WA | - |
testcase_05 | WA | - |
testcase_06 | WA | - |
testcase_07 | TLE | - |
testcase_08 | TLE | - |
testcase_09 | TLE | - |
testcase_10 | TLE | - |
testcase_11 | TLE | - |
testcase_12 | TLE | - |
testcase_13 | TLE | - |
testcase_14 | TLE | - |
testcase_15 | TLE | - |
testcase_16 | TLE | - |
testcase_17 | TLE | - |
testcase_18 | TLE | - |
testcase_19 | TLE | - |
testcase_20 | TLE | - |
testcase_21 | TLE | - |
ソースコード
from collections import deque class LCA: def __init__(self, size): self.size = size self.level = (size - 1).bit_length() self.edges = [[] for _ in range(size)] self.depth = [0] * size self.length = [float('inf')] * size self.prev = [None] * size self.kprev = None def addEdge(self, fr, to, cost=1): self.edges[fr].append((to, cost)) self.edges[to].append((fr, cost)) def dfs(self): st = deque([(0, 0)]) self.depth[0] = 0 self.length[0] = 0 while st: now, prev = st.pop() for to, cost in self.edges[now]: if to == prev: continue st.append((to, now)) self.depth[to] = self.depth[now] + 1 self.length[to] = self.length[now] + cost self.prev[to] = now def construct(self): self.dfs() kprev = [self.prev] S = self.prev for _ in range(self.level): T = [0] * self.size for i in range(self.size): if S[i] is None: continue T[i] = S[S[i]] kprev.append(T) S = T self.kprev = kprev def lca(self, u, v): dist = self.depth[v] - self.depth[u] if dist < 0: u, v = v, u dist = -dist for k in range(self.level + 1): if dist & 1: v = self.kprev[k][v] dist //= 2 if u == v: return u for k in range(self.level)[:: -1]: prevU = self.kprev[k][u] prevV = self.kprev[k][v] if prevU != prevV: u = prevU v = prevV return self.kprev[0][u] def dist(self, u, v): return self.length[u] + self.length[v] - self.length[self.lca(u, v)] * 2 N = int(input()) tree = LCA(N) for _ in range(N - 1): fr, to, cost = map(int, input().split()) tree.addEdge(fr, to, cost) tree.construct() Q = int(input()) ans = [] for _ in range(Q): x, y, z = map(int, input().split()) ans.append(min( tree.dist(x, y) + tree.dist(tree.lca(x, z), z), tree.dist(y, z) + tree.dist(tree.lca(z, y), x), tree.dist(z, x) + tree.dist(tree.lca(y, x), y), )) print(*ans, sep='\n')