結果

問題 No.386 貪欲な領主
ユーザー terasaterasa
提出日時 2023-01-15 16:26:06
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 686 ms / 2,000 ms
コード長 4,400 bytes
コンパイル時間 1,612 ms
コンパイル使用メモリ 86,968 KB
実行使用メモリ 110,560 KB
最終ジャッジ日時 2023-08-28 08:46:03
合計ジャッジ時間 7,647 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 165 ms
80,308 KB
testcase_01 AC 164 ms
79,984 KB
testcase_02 AC 161 ms
80,220 KB
testcase_03 AC 165 ms
80,172 KB
testcase_04 AC 423 ms
110,560 KB
testcase_05 AC 616 ms
108,740 KB
testcase_06 AC 686 ms
109,052 KB
testcase_07 AC 191 ms
82,464 KB
testcase_08 AC 274 ms
85,208 KB
testcase_09 AC 200 ms
82,504 KB
testcase_10 AC 164 ms
80,268 KB
testcase_11 AC 165 ms
80,456 KB
testcase_12 AC 188 ms
82,696 KB
testcase_13 AC 237 ms
84,352 KB
testcase_14 AC 644 ms
108,772 KB
testcase_15 AC 383 ms
110,512 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from typing import List, Tuple, Callable, TypeVar, Optional
import sys
import itertools
import heapq
import bisect
import math
from collections import deque, defaultdict
from functools import lru_cache, cmp_to_key

input = sys.stdin.readline

if __file__ != 'prog.py':
    sys.setrecursionlimit(10 ** 6)


def readints(): return map(int, input().split())
def readlist(): return list(readints())
def readstr(): return input()[:-1]
def readlist1(): return list(map(lambda x: int(x) - 1, input().split()))


class CumulativeSum:
    def __init__(self, A):
        self.S = [0]
        acc = 0
        for a in A:
            acc += a
            self.S.append(acc)

    def get(self, l, r):
        """return sum(A[l:r]), i.e. sum of A[x] (l <= x < r) """
        return self.S[r] - self.S[l]


class HLD:
    # reference: https://codeforces.com/blog/entry/53170
    def __init__(self, N, E, root: int = 0):
        self.N = N
        self.E = E
        self.root = root

        self.D = [0] * self.N
        self.par = [-1] * self.N
        self.sz = [0] * self.N
        self.top = [0] * self.N

        self.ord = [None] * self.N

        self._dfs_sz()
        self._dfs_hld()

    def path_query_range(self, u: int, v: int, is_edge_query: bool = False) -> List[Tuple[int, int]]:
        """return list of [l, r) ranges that cover u-v path"""
        ret = []
        while True:
            if self.ord[u] > self.ord[v]:
                u, v = v, u
            if self.top[u] == self.top[v]:
                ret.append((self.ord[u] + is_edge_query, self.ord[v] + 1))
                return ret
            ret.append((self.ord[self.top[v]], self.ord[v] + 1))
            v = self.par[self.top[v]]

    def subtree_query_range(self, v: int, is_edge_query: bool = False) -> Tuple[int, int]:
        """return [l, r) range that cover vertices of subtree v"""
        return (self.ord[v] + is_edge_query, self.ord[v] + self.sz[v])

    def get_index(self, v: int) -> int:
        """return euler tour order of given vertex"""
        return self.ord[v]

    def lca(self, u, v):
        while True:
            if self.ord[u] > self.ord[v]:
                u, v = v, u
            if self.top[u] == self.top[v]:
                return u
            v = self.par[self.top[v]]

    def dist(self, u, v):
        return self.D[u] + self.D[v] - 2 * self.D[self.lca(u, v)]

    def _dfs_sz(self):
        stack = [(self.root, -1)]
        while stack:
            v, p = stack.pop()
            if v < 0:
                v = ~v
                self.sz[v] = 1
                for i, dst in enumerate(self.E[v]):
                    if dst == p:
                        continue
                    self.sz[v] += self.sz[dst]
                    # v -> E[v][0] will be heavy path
                    if self.sz[self.E[v][0]] < self.sz[dst]:
                        self.E[v][0], self.E[v][i] = self.E[v][i], self.E[v][0]
            else:
                if ~p:
                    self.D[v] = self.D[p] + 1
                    self.par[v] = p
                # avoid first element of E[v] is parent of vertex v if v has some children
                if len(self.E[v]) >= 2 and self.E[v][0] == p:
                    self.E[v][0], self.E[v][1] = self.E[v][1], self.E[v][0]
                stack.append((~v, p))
                for dst in self.E[v]:
                    if dst == p:
                        continue
                    stack.append((dst, v))

    def _dfs_hld(self):
        stack = [(self.root, -1)]
        cnt = 0
        while stack:
            v, p = stack.pop()
            self.ord[v] = cnt
            cnt += 1
            heavy_path_idx = len(self.E[v]) - 1
            for i, dst in enumerate(self.E[v][::-1]):
                if dst == p:
                    continue
                # top[dst] is top[v] if v -> dst is heavy path otherwise dst itself
                self.top[dst] = self.top[v] if i == heavy_path_idx else dst
                stack.append((dst, v))


N = int(input())
E = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = readints()
    E[a].append(b)
    E[b].append(a)
solver = HLD(N, E)
A = [None] * N
for i in range(N):
    u = int(input())
    A[solver.get_index(i)] = u
S = CumulativeSum(A)
Q = int(input())
ans = 0
for _ in range(Q):
    a, b, c = readints()
    for l, r in solver.path_query_range(a, b):
        ans += S.get(l, r) * c
print(ans)
0