結果
問題 | No.1094 木登り / Climbing tree |
ユーザー | qib |
提出日時 | 2022-11-04 00:04:17 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,942 ms / 2,000 ms |
コード長 | 1,225 bytes |
コンパイル時間 | 718 ms |
コンパイル使用メモリ | 86,860 KB |
実行使用メモリ | 148,112 KB |
最終ジャッジ日時 | 2023-09-25 06:59:50 |
合計ジャッジ時間 | 43,314 ms |
ジャッジサーバーID (参考情報) |
judge12 / judge11 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 89 ms
71,344 KB |
testcase_01 | AC | 1,942 ms
147,616 KB |
testcase_02 | AC | 369 ms
141,312 KB |
testcase_03 | AC | 579 ms
83,384 KB |
testcase_04 | AC | 571 ms
108,616 KB |
testcase_05 | AC | 786 ms
138,844 KB |
testcase_06 | AC | 1,000 ms
100,796 KB |
testcase_07 | AC | 1,633 ms
147,568 KB |
testcase_08 | AC | 1,659 ms
148,112 KB |
testcase_09 | AC | 1,665 ms
147,696 KB |
testcase_10 | AC | 1,648 ms
147,684 KB |
testcase_11 | AC | 1,624 ms
147,792 KB |
testcase_12 | AC | 1,610 ms
147,480 KB |
testcase_13 | AC | 1,743 ms
147,732 KB |
testcase_14 | AC | 1,657 ms
147,800 KB |
testcase_15 | AC | 920 ms
94,000 KB |
testcase_16 | AC | 1,131 ms
129,552 KB |
testcase_17 | AC | 1,016 ms
109,660 KB |
testcase_18 | AC | 980 ms
102,168 KB |
testcase_19 | AC | 1,105 ms
120,596 KB |
testcase_20 | AC | 1,687 ms
147,704 KB |
testcase_21 | AC | 1,102 ms
111,676 KB |
testcase_22 | AC | 1,644 ms
147,564 KB |
testcase_23 | AC | 1,636 ms
147,248 KB |
testcase_24 | AC | 1,626 ms
146,292 KB |
testcase_25 | AC | 1,768 ms
147,296 KB |
testcase_26 | AC | 1,616 ms
146,168 KB |
ソースコード
from collections import deque n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): a, b, c = map(int, input().split()) a -= 1 b -= 1 g[a].append((b, c)) g[b].append((a, c)) k = n.bit_length() src = 0 doub = [[src for _ in range(n)] for _ in range(k)] depth = [None for _ in range(n)] depth[src] = 0 cost = [0 for _ in range(n)] dq = deque() dq.appendleft(src) while len(dq) > 0: cur = dq.pop() for nxt, c in g[cur]: if not depth[nxt] is None: continue depth[nxt] = depth[cur] + 1 cost[nxt] = cost[cur] + c doub[0][nxt] = cur dq.appendleft(nxt) for i in range(1, k): for v in range(n): doub[i][v] = doub[i - 1][doub[i - 1][v]] def lca(u, v): ut = u vt = v if depth[ut] > depth[vt]: ut, vt = vt, ut diff = depth[vt] - depth[ut] for i in range(k): if (diff >> i) & 1 != 0: vt = doub[i][vt] if ut != vt: for i in range(k - 1, -1, -1): if doub[i][ut] != doub[i][vt]: ut = doub[i][ut] vt = doub[i][vt] if ut != vt: ut = doub[0][ut] return ut q = int(input()) for _ in range(q): s, t = map(int, input().split()) s -= 1 t -= 1 l = lca(s, t) print(cost[s] + cost[t] - 2 * cost[l])