結果

問題 No.1054 Union add query
ユーザー 草苺奶昔草苺奶昔
提出日時 2023-03-14 10:45:42
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 892 ms / 2,000 ms
コード長 1,785 bytes
コンパイル時間 153 ms
コンパイル使用メモリ 81,728 KB
実行使用メモリ 91,108 KB
最終ジャッジ日時 2023-10-18 11:31:23
合計ジャッジ時間 7,746 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 61 ms
68,204 KB
testcase_01 AC 62 ms
68,204 KB
testcase_02 AC 61 ms
68,204 KB
testcase_03 AC 892 ms
81,992 KB
testcase_04 AC 870 ms
91,108 KB
testcase_05 AC 889 ms
80,876 KB
testcase_06 AC 733 ms
83,932 KB
testcase_07 AC 653 ms
83,928 KB
testcase_08 AC 622 ms
84,192 KB
testcase_09 AC 856 ms
90,660 KB
testcase_10 AC 317 ms
90,176 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict
from typing import DefaultDict, Generic, Hashable, Iterable, List, Optional, TypeVar


T = TypeVar("T", bound=Hashable)


class UnionFindWithGroupAdd:
    """维护分量之和并查集(区间加,单点查询)"""

    __slots__ = ("_parent", "_rank", "_lazy")

    def __init__(self, n: int):
        self._parent = list(range(n))
        self._rank = [1] * n
        self._lazy = [0] * n  # !e()

    def find(self, x: int) -> int:
        while self._parent[x] != x:
            x = self._parent[x]
        return x

    def union(self, x: int, y: int) -> bool:
        x, y = self.find(x), self.find(y)
        if x == y:
            return False
        if self._rank[x] < self._rank[y]:
            x, y = y, x
        self._rank[x] += self._rank[y]
        self._parent[y] = x
        self._lazy[y] -= self._lazy[x]  # !inv()
        return True

    def isConnected(self, x: int, y: int) -> bool:
        return self.find(x) == self.find(y)

    def getSize(self, x: int) -> int:
        return self._rank[self.find(x)]

    def add(self, group: int, delta: int) -> None:
        self._lazy[self.find(group)] += delta

    def get(self, x: int) -> int:
        res = 0
        while self._parent[x] != x:
            res += self._lazy[x]  # !op()
            x = self._parent[x]
        return res + self._lazy[x]  # !op()


if __name__ == "__main__":
    # https://yukicoder.me/problems/no/1054
    n, q = map(int, input().split())
    uf = UnionFindWithGroupAdd(n)
    for _ in range(q):
        op, a, b = map(int, input().split())
        if op == 1:
            a, b = a - 1, b - 1
            uf.union(a, b)
        elif op == 2:
            a -= 1
            uf.add(a, b)
        else:
            a -= 1
            print(uf.get(a))
0