結果

問題 No.898 tri-βutree
ユーザー tktk_snsntktk_snsn
提出日時 2020-06-05 19:34:29
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,134 ms / 4,000 ms
コード長 1,724 bytes
コンパイル時間 1,125 ms
コンパイル使用メモリ 87,104 KB
実行使用メモリ 204,152 KB
最終ジャッジ日時 2023-08-08 16:49:36
合計ジャッジ時間 20,220 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 277 ms
118,484 KB
testcase_01 AC 90 ms
71,504 KB
testcase_02 AC 100 ms
76,520 KB
testcase_03 AC 101 ms
76,428 KB
testcase_04 AC 102 ms
76,432 KB
testcase_05 AC 101 ms
76,516 KB
testcase_06 AC 101 ms
76,372 KB
testcase_07 AC 1,105 ms
202,212 KB
testcase_08 AC 1,097 ms
203,424 KB
testcase_09 AC 1,083 ms
203,632 KB
testcase_10 AC 1,098 ms
202,908 KB
testcase_11 AC 1,108 ms
202,912 KB
testcase_12 AC 1,103 ms
203,016 KB
testcase_13 AC 1,104 ms
202,120 KB
testcase_14 AC 1,134 ms
203,352 KB
testcase_15 AC 1,089 ms
203,268 KB
testcase_16 AC 1,117 ms
204,152 KB
testcase_17 AC 1,132 ms
203,312 KB
testcase_18 AC 1,093 ms
203,316 KB
testcase_19 AC 1,100 ms
203,820 KB
testcase_20 AC 1,090 ms
201,644 KB
testcase_21 AC 1,104 ms
203,480 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
D = N.bit_length()
edge = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b, c = map(int, input().split())
    edge[a].append((b, c))
    edge[b].append((a, c))
Q = int(input())
query = [sorted(list(map(int, input().split()))) for _ in range(Q)]


root = 0
dist = [-1] * N
dist[root] = 0
depth = [0] * N
parent = [[-1] * N for _ in range(D)]

node = [root]
while node:
    s = node.pop()
    d = dist[s]
    dep = depth[s]
    for t, c in edge[s]:
        if dist[t] != -1:
            continue
        dist[t] = d + c
        depth[t] = dep + 1
        node.append(t)
        parent[0][t] = s

for i in range(D - 1):
    for j in range(N):
        parent[i + 1][j] = parent[i][parent[i][j]]


def lower_ancester(x, h):
    for i in reversed(range(D)):
        if h >= (1 << i):
            h -= (1 << i)
            x = parent[i][x]
    return x


def LCA(u, v):
    if depth[u] < depth[v]:
        u, v = v, u
    u = lower_ancester(u, depth[u] - depth[v])
    if u == v:
        return u
    for i in reversed(range(D)):
        if parent[i][u] != parent[i][v]:
            u = parent[i][u]
            v = parent[i][v]
    return parent[0][u]


path = defaultdict(int)
for x, y, z in query:
    if not path[(x, y)]:
        lca = LCA(x, y)
        path[(x, y)] = dist[x] + dist[y] - 2 * dist[lca]
    if not path[(y, z)]:
        lca = LCA(y, z)
        path[(y, z)] = dist[y] + dist[z] - 2 * dist[lca]
    if not path[(x, z)]:
        lca = LCA(x, z)
        path[(x, z)] = dist[x] + dist[z] - 2 * dist[lca]
    size = (path[(x, y)] + path[(y, z)] + path[(x, z)]) // 2
    print(size)
0