結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-03-14 10:47:03 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 367 ms / 2,000 ms |
| コード長 | 1,857 bytes |
| コンパイル時間 | 251 ms |
| コンパイル使用メモリ | 82,504 KB |
| 実行使用メモリ | 92,356 KB |
| 最終ジャッジ日時 | 2024-09-18 07:55:30 |
| 合計ジャッジ時間 | 4,050 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
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
import sys
read = sys.stdin.read
input = sys.stdin.readline
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))