結果

問題 No.1094 木登り / Climbing tree
ユーザー noriocnorioc
提出日時 2021-07-12 08:52:44
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 2,149 bytes
コンパイル時間 386 ms
コンパイル使用メモリ 11,056 KB
実行使用メモリ 117,684 KB
最終ジャッジ日時 2023-09-14 20:27:19
合計ジャッジ時間 9,362 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 20 ms
8,852 KB
testcase_01 TLE -
testcase_02 -- -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import collections


class LCA:
    def __init__(self, n, adj):
        K = 1
        while (1 << K) < n: K += 1
        self.parent = [[-1] * n for _ in range(K)]
        self.dist = [-1] * n
        self.cost = [-1] * n
        self._dfs2(node=0, par=-1, d=0, adj=adj)
        for k in range(K-1):
            for v in range(n):
                if self.parent[k][v] < 0:
                    self.parent[k+1][v] = -1
                else:
                    self.parent[k+1][v] = self.parent[k][self.parent[k][v]]

    def _dfs2(self, node, par, d, adj):
        s = [(node, par, d, 0)]
        while s:
            node, par, d, c = s.pop()
            self.parent[0][node] = par
            self.dist[node] = d
            self.cost[node] = c
            for nd, cost in adj[node]:
                if nd == par: continue
                s.append((nd, node, d + 1, c + cost))

    def query(self, u: int, v: int) -> int:
        if self.dist[u] < self.dist[v]: u, v = v, u
        K = len(self.parent)
        # LCA までの距離を同じにする
        for k in range(K):
            if (self.dist[u] - self.dist[v]) >> k & 1:
                u = self.parent[k][u]
        # 二分探索で LCA を求める
        if u == v: return u
        for k in range(K-1, -1, -1):
            if self.parent[k][u] != self.parent[k][v]:
                u = self.parent[k][u]
                v = self.parent[k][v]
        return self.parent[0][u]

    def distance(self, u: int, v: int) -> int:
        return self.dist[u] + self.dist[v] - 2 * self.dist[self.query(u, v)]

    def get_cost(self, u: int, v: int) -> int:
        return self.cost[u] + self.cost[v] - 2 * self.cost[self.query(u, v)]

    def is_on_path(self, u, v, a) -> bool:
        return self.distance(u, a) + self.distance(a, v) == self.distance(u, v)


N = int(input())
adj = collections.defaultdict(list)
for i in range(N-1):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    adj[a].append((b, c))
    adj[b].append((a, c))

Q = int(input())
lca = LCA(N, adj)
for _ in range(Q):
    a, b = map(int, input().split())
    ans = lca.get_cost(a-1, b-1)
    print(ans)
0