結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2022-04-06 23:28:11 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 895 ms / 2,000 ms |
| コード長 | 1,481 bytes |
| コンパイル時間 | 255 ms |
| コンパイル使用メモリ | 82,852 KB |
| 実行使用メモリ | 188,928 KB |
| 最終ジャッジ日時 | 2024-11-27 21:02:45 |
| 合計ジャッジ時間 | 7,559 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
class Unionfind:
def __init__(self,n):
self.uf = [-1]*n
self.p = [[i] for i in range(n)]
self.count = [0]*n
def find(self,x):
if self.uf[x] < 0:
return x
else:
self.uf[x] = self.find(self.uf[x])
return self.uf[x]
def same(self,x,y):
return self.find(x) == self.find(y)
def union(self,x,y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.uf[x] > self.uf[y]:
x,y = y,x
cx = self.count[x]
cy = self.count[y]
for i in self.p[y]:
if i != y:
self.count[i] += cy-cx
else:
self.count[i] += -cx
self.p[x].append(i)
self.p[y] = []
self.uf[x] += self.uf[y]
self.uf[y] = x
return True
def size(self,x):
x = self.find(x)
return -self.uf[x]
def add(self,a,b):
self.count[self.find(a)] += b
def solve(self,a):
num = self.count[a]
if self.find(a) != a:
num += self.count[self.find(a)]
return num
n,q = map(int,input().split())
uf = Unionfind(n)
Q = [list(map(int,input().split())) for i in range(q)]
for t,a,b in Q:
if t == 1:
a,b = a-1,b-1
if uf.same(a,b):
continue
uf.union(a,b)
elif t == 2:
uf.add(a-1,b)
else:
print(uf.solve(a-1))