結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
maspy
|
| 提出日時 | 2020-05-16 11:17:37 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
AC
|
| 実行時間 | 1,584 ms / 2,000 ms |
| コード長 | 1,471 bytes |
| コンパイル時間 | 179 ms |
| コンパイル使用メモリ | 12,800 KB |
| 実行使用メモリ | 168,744 KB |
| 最終ジャッジ日時 | 2024-09-22 03:56:23 |
| 合計ジャッジ時間 | 9,638 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
class UnionFind:
def __init__(self, N):
self.root = list(range(N))
self.size = [1] * (N)
self.comp = [[v] for v in range(N)]
self.comp_val = [0] * N
self.val = [0] * N
def find_root(self, x):
root = self.root
while root[x] != x:
root[x] = root[root[x]]
x = root[x]
return x
def merge(self, x, y):
x = self.find_root(x)
y = self.find_root(y)
if x == y:
return False
sx, sy = self.size[x], self.size[y]
if sx < sy:
x, y = y, x
# x が大きい
self.size[x] += sy
self.root[y] = x
for v in self.comp[y]:
self.val[v] += self.comp_val[y] - self.comp_val[x]
self.comp[x] += self.comp[y]
self.comp[y].clear()
def get_val(self, v):
r = self.find_root(v)
return self.val[v] + self.comp_val[r]
def add_to_comp(self, v, x):
r = self.find_root(v)
self.comp_val[r] += x
def solve():
N, Q = map(int, readline().split())
m = map(int, read().split())
uf = UnionFind(N + 1)
for t, a, b in zip(m, m, m):
if t == 1:
uf.merge(a, b)
elif t == 2:
uf.add_to_comp(a, b)
else:
yield uf.get_val(a)
print('\n'.join(map(str, solve())))
maspy