結果
問題 | No.898 tri-βutree |
ユーザー | polylogK |
提出日時 | 2019-09-18 01:04:31 |
言語 | PyPy3 (7.3.15) |
結果 |
RE
(最新)
AC
(最初)
|
実行時間 | - |
コード長 | 1,734 bytes |
コンパイル時間 | 549 ms |
コンパイル使用メモリ | 82,560 KB |
実行使用メモリ | 140,528 KB |
最終ジャッジ日時 | 2024-11-08 21:42:54 |
合計ジャッジ時間 | 28,356 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | RE | - |
testcase_01 | AC | 43 ms
52,608 KB |
testcase_02 | AC | 60 ms
63,404 KB |
testcase_03 | AC | 61 ms
62,976 KB |
testcase_04 | AC | 58 ms
62,776 KB |
testcase_05 | AC | 58 ms
62,464 KB |
testcase_06 | AC | 60 ms
63,104 KB |
testcase_07 | AC | 1,662 ms
140,064 KB |
testcase_08 | AC | 1,663 ms
138,216 KB |
testcase_09 | AC | 1,645 ms
138,980 KB |
testcase_10 | AC | 1,701 ms
138,596 KB |
testcase_11 | AC | 1,676 ms
138,872 KB |
testcase_12 | AC | 1,672 ms
138,692 KB |
testcase_13 | AC | 1,722 ms
139,556 KB |
testcase_14 | AC | 1,640 ms
138,212 KB |
testcase_15 | AC | 1,619 ms
140,528 KB |
testcase_16 | AC | 1,663 ms
139,540 KB |
testcase_17 | AC | 1,681 ms
139,060 KB |
testcase_18 | AC | 1,672 ms
139,700 KB |
testcase_19 | AC | 1,582 ms
138,560 KB |
testcase_20 | AC | 1,620 ms
138,864 KB |
testcase_21 | AC | 1,654 ms
139,008 KB |
ソースコード
class lowest_common_ancestor: logN = 20 def __init__(self, N): self.g = [[] for i in range(N)] self.parent = [[-1 for i in range(N)] for i in range(self.logN)] self.depth = [0 for i in range(N)] def add_edge(self, u, v): self.g[u].append(v) self.g[v].append(u) def dfs(self, v, par = -1, d = 0): self.parent[0][v] = par self.depth[v] = d for e in self.g[v]: if e == par: continue self.dfs(e, v, d + 1) def build(self): self.dfs(0) for k in range(self.logN - 1): for i in range(len(self.g)): if self.parent[k][i] == -1: self.parent[k + 1][i] = -1 else: self.parent[k + 1][i] = self.parent[k][self.parent[k][i]] def query(self, u, v): if self.depth[u] > self.depth[v]: u, v = v, u for k in range(self.logN): if (((self.depth[v] - self.depth[u]) >> k) & 1) == 1: v = self.parent[k][v] if u == v: return u for k in range(self.logN - 1, -1, -1): if self.parent[k][u] == self.parent[k][v]: continue u = self.parent[k][u] v = self.parent[k][v] return self.parent[0][u] g = [[]] dist = [] def dfs(v, par): for e in g[v]: if e[0] == par: continue dist[e[0]] = dist[v] + e[1] dfs(e[0], v) lca = lowest_common_ancestor(0) def calc(u, v): c = lca.query(u, v) return dist[u] + dist[v] - 2 * dist[c] if __name__ == "__main__": N = int(input()) g = [[] for i in range(N)] lca = lowest_common_ancestor(N) for i in range(N - 1): a, b, c = map(int, input().split()) g[a].append([b, c]) g[b].append([a, c]) lca.add_edge(a, b) lca.build() dist = [0 for i in range(N)] dfs(0, -1) Q = int(input()) for _ in range(Q): a, b, c = map(int, input().split()) print((calc(a, b) + calc(b, c) + calc(c, a)) >> 1)