結果

問題 No.386 貪欲な領主
ユーザー maspymaspy
提出日時 2020-03-19 14:25:35
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 739 ms / 2,000 ms
コード長 2,095 bytes
コンパイル時間 338 ms
コンパイル使用メモリ 11,144 KB
実行使用メモリ 102,284 KB
最終ジャッジ日時 2023-08-20 20:50:05
合計ジャッジ時間 8,394 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 133 ms
29,804 KB
testcase_01 AC 128 ms
29,704 KB
testcase_02 AC 135 ms
29,840 KB
testcase_03 AC 138 ms
29,792 KB
testcase_04 AC 668 ms
102,284 KB
testcase_05 AC 739 ms
92,136 KB
testcase_06 AC 730 ms
91,740 KB
testcase_07 AC 137 ms
30,488 KB
testcase_08 AC 191 ms
38,668 KB
testcase_09 AC 144 ms
30,864 KB
testcase_10 AC 132 ms
29,820 KB
testcase_11 AC 132 ms
29,768 KB
testcase_12 AC 139 ms
30,168 KB
testcase_13 AC 153 ms
31,908 KB
testcase_14 AC 726 ms
91,592 KB
testcase_15 AC 619 ms
96,608 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/ python3.8
# %%
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np

N = int(readline())
graph = [[] for _ in range(N + 1)]
for _ in range(N - 1):
    a, b = map(int, readline().split())
    a += 1
    b += 1
    graph[a].append(b)
    graph[b].append(a)

cost = (0,) + tuple(int(readline()) for _ in range(N))
Q = int(readline())
ABM = np.array(read().split(), np.int64)
A = ABM[::3] + 1
B = ABM[1::3] + 1
M = ABM[2::3]


def EulerTour(graph, root=1):
    V = len(graph)
    par = [0] * V
    depth = [0] * V
    dist = [0] * V
    dist[1] = cost[1]
    depth[root] = 0
    tour = [root]
    st = [root]
    while st:
        x = st[-1]
        if not graph[x]:
            st.pop()
            tour.append(par[x])
            continue
        y = graph[x].pop()
        if y == par[x]:
            continue
        par[y] = x
        depth[y] = depth[x] + 1
        dist[y] = dist[x] + cost[y]
        st.append(y)
        tour.append(y)
    return par, tour, depth, dist


par, tour, depth, dist = EulerTour(graph)

Ltour = len(tour)
tour_arr = np.array(tour)
depth_arr = np.array(depth)
tour_d = depth_arr[tour_arr]
idx = np.arange(len(depth))
idx[tour_arr] = np.arange(Ltour)

sp = np.empty((Ltour.bit_length(), Ltour), np.int32)
sp[0] = np.arange(Ltour)
for n in range(1, Ltour.bit_length()):
    prev, width = sp[n - 1], 1 << (n - 1)
    x = prev[:-width]
    y = prev[width:]
    condition = tour_d[x] > tour_d[y]
    sp[n] = prev
    sp[n, :-width][condition] = y[condition]


def LCA(A, B):
    AB = np.vstack([A, B]).T
    LR = idx[AB]
    LR.sort(axis=1)
    # [L,R] におけるRmQ
    L = LR[:, 0]
    R = LR[:, 1]
    x = R - L
    n = np.zeros_like(x)  # 2^n <= R-L
    for _ in range(20):
        x >>= 1
        n[x > 0] += 1
    x = sp[n, L]
    y = sp[n, R - (1 << n) + 1]
    return np.where(tour_d[x] < tour_d[y], tour_arr[x], tour_arr[y])


C = LCA(A, B)
dist = np.array(dist)
cost = np.array(cost)
answer = ((dist[A] + dist[B] - 2 * dist[C] + cost[C]) * M).sum()
print(answer)
0