結果
問題 | No.898 tri-βutree |
ユーザー | rlangevin |
提出日時 | 2023-05-10 23:18:19 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,232 ms / 4,000 ms |
コード長 | 2,392 bytes |
コンパイル時間 | 203 ms |
コンパイル使用メモリ | 82,304 KB |
実行使用メモリ | 111,008 KB |
最終ジャッジ日時 | 2024-11-27 03:00:15 |
合計ジャッジ時間 | 17,160 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 408 ms
111,008 KB |
testcase_01 | AC | 39 ms
52,352 KB |
testcase_02 | AC | 53 ms
63,104 KB |
testcase_03 | AC | 54 ms
63,104 KB |
testcase_04 | AC | 55 ms
63,360 KB |
testcase_05 | AC | 54 ms
63,360 KB |
testcase_06 | AC | 59 ms
64,640 KB |
testcase_07 | AC | 855 ms
110,832 KB |
testcase_08 | AC | 865 ms
110,492 KB |
testcase_09 | AC | 855 ms
110,540 KB |
testcase_10 | AC | 878 ms
110,664 KB |
testcase_11 | AC | 1,232 ms
110,644 KB |
testcase_12 | AC | 867 ms
110,444 KB |
testcase_13 | AC | 855 ms
110,352 KB |
testcase_14 | AC | 856 ms
110,212 KB |
testcase_15 | AC | 875 ms
110,780 KB |
testcase_16 | AC | 922 ms
110,600 KB |
testcase_17 | AC | 892 ms
110,232 KB |
testcase_18 | AC | 893 ms
110,640 KB |
testcase_19 | AC | 901 ms
110,840 KB |
testcase_20 | AC | 871 ms
110,424 KB |
testcase_21 | AC | 864 ms
110,824 KB |
ソースコード
import sys input = sys.stdin.readline class LowestCommonAncestor: def __init__(self, n): self._n = n self._logn = 0 v = 1 while v <= self._n: v *= 2 self._logn += 1 self._depth = [0] * self._n self._distance = [0] * self._n self._ancestor = [[-1] * self._n for _ in range(self._logn)] self._G = [[] for i in range(self._n)] def add_edge(self, u, v, w=1): self._G[u].append((v, w)) self._G[v].append((u, w)) def build(self, root=0): stack = [root] while stack: cur = stack.pop() for nex, w in self._G[cur]: if self._ancestor[0][nex] != cur and self._ancestor[0][cur] != nex: self._ancestor[0][nex] = cur self._depth[nex] = self._depth[cur] + 1 self._distance[nex] = self._distance[cur] + w stack.append(nex) for k in range(1, self._logn): for i in range(self._n): if self._ancestor[k - 1][i] == -1: self._ancestor[k][i] = -1 else: self._ancestor[k][i] = self._ancestor[k - 1][self._ancestor[k - 1][i]] def lca(self, u, v): if self._depth[u] > self._depth[v]: u, v = v, u for k in range(self._logn - 1, -1, -1): if ((self._depth[v] - self._depth[u]) >> k) & 1: v = self._ancestor[k][v] if u == v: return u for k in range(self._logn - 1, -1, -1): if self._ancestor[k][u] != self._ancestor[k][v]: u = self._ancestor[k][u] v = self._ancestor[k][v] return self._ancestor[0][u] def distance(self, u, v): return self._distance[u] + self._distance[v] - 2 * self._distance[self.lca(u, v)] N = int(input()) T = LowestCommonAncestor(N) for i in range(N - 1): u, v, w = map(int, input().split()) T.add_edge(u, v, w) T.build() Q = int(input()) for _ in range(Q): L = list(map(int, input().split())) ans = 10 ** 18 for i in range(3): ans = min(ans, T.distance(L[i], L[(i + 1)%3]) + T.distance(T.lca(L[i], L[(i + 1)%3]), L[(i + 2)%3])) print(ans)