結果

問題 No.399 動的な領主
ユーザー terasaterasa
提出日時 2023-01-14 11:11:34
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,085 ms / 2,000 ms
コード長 5,677 bytes
コンパイル時間 237 ms
コンパイル使用メモリ 82,140 KB
実行使用メモリ 102,068 KB
最終ジャッジ日時 2024-06-07 13:18:03
合計ジャッジ時間 12,134 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 68 ms
67,712 KB
testcase_01 AC 67 ms
67,712 KB
testcase_02 AC 73 ms
71,808 KB
testcase_03 AC 73 ms
71,552 KB
testcase_04 AC 159 ms
79,744 KB
testcase_05 AC 257 ms
82,092 KB
testcase_06 AC 1,085 ms
98,600 KB
testcase_07 AC 1,055 ms
98,728 KB
testcase_08 AC 1,052 ms
98,992 KB
testcase_09 AC 1,050 ms
99,024 KB
testcase_10 AC 157 ms
79,104 KB
testcase_11 AC 216 ms
81,812 KB
testcase_12 AC 840 ms
100,916 KB
testcase_13 AC 828 ms
101,512 KB
testcase_14 AC 283 ms
100,992 KB
testcase_15 AC 385 ms
100,864 KB
testcase_16 AC 511 ms
102,068 KB
testcase_17 AC 1,074 ms
99,208 KB
testcase_18 AC 1,041 ms
99,072 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from typing import List, Tuple, Callable, TypeVar
import sys

input = sys.stdin.readline


T = TypeVar('T')


class DualSegTree:
    # reference: https://hackmd.io/@tatyam-prime/DualSegmentTree
    def __init__(self, N: int, f: Callable[[T, T], T], e: T):
        """双対セグメント木

        Args:
            N (int): 配列の長さ
            f (Callable[[T, T], T]): 作用させる関数
            e (T): 単位元

        Note:
            値に作用を適応させる操作(遅延セグメント木のmappingに相当)と、
            作用を合成する操作(遅延セグメント木のcompositionに相当)が、
            同一の操作として記述できることが必要
            例) 区間加算・区間代入・区間chmin等
        """
        self.N = N
        self.f = f
        self.e = e

        self.K = (self.N - 1).bit_length()
        self.size = 1 << self.K

        self.lazy = [e] * (self.size << 1)

    def build(self, A: List[T]) -> None:
        for i in range(self.N):
            self.lazy[self.size + i] = A[i]

    def _propagate_at(self, i: int) -> None:
        if self.lazy[i] == self.e:
            return
        self.lazy[i << 1] = self.f(self.lazy[i << 1], self.lazy[i])
        self.lazy[i << 1 | 1] = self.f(self.lazy[i << 1 | 1], self.lazy[i])
        self.lazy[i] = self.e

    def _propagate_above(self, i: int) -> None:
        H = i.bit_length() - 1
        for h in range(H, 0, -1):
            self._propagate_at(i >> h)

    def get(self, i: int) -> T:
        i += self.size
        self._propagate_above(i)
        return self.lazy[i]

    def set(self, i: int, a: T) -> None:
        i += self.size
        self._propagate_above(i)
        self.lazy[i] = a

    def query(self, l: int, r: int, a: T) -> None:
        assert 0 <= l and l <= r and r <= self.N
        l += self.size
        r += self.size
        self._propagate_above(l // (l & -l))
        self._propagate_above(r // (r & -r) - 1)
        while l < r:
            if l & 1:
                self.lazy[l] = self.f(self.lazy[l], a)
                l += 1
            if r & 1:
                r -= 1
                self.lazy[r] = self.f(self.lazy[r], a)
            l >>= 1
            r >>= 1


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) -> Tuple[int, int]:
        """return [l, r) range that cover vertices of subtree v"""
        return (self.ord[v], self.ord[v] + self.sz[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 _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[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):
    u, v = map(int, input().split())
    u -= 1
    v -= 1
    E[u].append(v)
    E[v].append(u)

solver = HLD(N, E)
dst = DualSegTree(N, lambda a, b: a + b, 0)
Q = int(input())
for _ in range(Q):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    for l, r in solver.path_query_range(a, b):
        dst.query(l, r, 1)
ans = 0
for i in range(N):
    cnt = dst.get(i)
    ans += (1 + cnt) * cnt // 2
print(ans)
0