結果
問題 | No.898 tri-βutree |
ユーザー | OKCH3COOH |
提出日時 | 2019-10-26 22:15:53 |
言語 | Python3 (3.12.2 + numpy 1.26.4 + scipy 1.12.0) |
結果 |
AC
|
実行時間 | 3,237 ms / 4,000 ms |
コード長 | 2,242 bytes |
コンパイル時間 | 210 ms |
コンパイル使用メモリ | 12,672 KB |
実行使用メモリ | 70,272 KB |
最終ジャッジ日時 | 2024-09-14 19:11:01 |
合計ジャッジ時間 | 55,689 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 1,705 ms
68,224 KB |
testcase_01 | AC | 30 ms
10,880 KB |
testcase_02 | AC | 32 ms
11,008 KB |
testcase_03 | AC | 32 ms
10,880 KB |
testcase_04 | AC | 32 ms
10,880 KB |
testcase_05 | AC | 32 ms
11,008 KB |
testcase_06 | AC | 32 ms
11,008 KB |
testcase_07 | AC | 3,141 ms
70,016 KB |
testcase_08 | AC | 3,095 ms
70,016 KB |
testcase_09 | AC | 3,186 ms
70,016 KB |
testcase_10 | AC | 3,178 ms
70,016 KB |
testcase_11 | AC | 3,179 ms
70,272 KB |
testcase_12 | AC | 3,111 ms
70,016 KB |
testcase_13 | AC | 3,208 ms
70,144 KB |
testcase_14 | AC | 3,216 ms
70,016 KB |
testcase_15 | AC | 3,188 ms
70,016 KB |
testcase_16 | AC | 3,154 ms
70,144 KB |
testcase_17 | AC | 3,158 ms
70,272 KB |
testcase_18 | AC | 3,237 ms
70,144 KB |
testcase_19 | AC | 3,212 ms
69,888 KB |
testcase_20 | AC | 3,186 ms
70,016 KB |
testcase_21 | AC | 3,163 ms
70,016 KB |
ソースコード
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((tree.dist(x, y) + tree.dist(y, z) + tree.dist(z, x)) // 2) print(*ans, sep='\n')