結果

問題 No.1054 Union add query
ユーザー roarisroaris
提出日時 2020-11-17 13:29:04
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 668 ms / 2,000 ms
コード長 1,770 bytes
コンパイル時間 361 ms
コンパイル使用メモリ 87,236 KB
実行使用メモリ 146,372 KB
最終ジャッジ日時 2023-09-30 14:11:10
合計ジャッジ時間 6,559 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,624 KB
testcase_01 AC 69 ms
71,144 KB
testcase_02 AC 68 ms
71,404 KB
testcase_03 AC 546 ms
100,308 KB
testcase_04 AC 668 ms
146,372 KB
testcase_05 AC 464 ms
91,068 KB
testcase_06 AC 403 ms
113,620 KB
testcase_07 AC 349 ms
113,760 KB
testcase_08 AC 391 ms
113,404 KB
testcase_09 AC 370 ms
136,832 KB
testcase_10 AC 253 ms
134,660 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
        self.comp = [[i] for i in range(n)]
        self.rp = [0]*n
        self.vp = [0]*n
    
    def root(self, x):
        r = x
        
        while not self.par[r]<0:
            r = self.par[r]
        
        t = x
        
        while t!=r:
            tmp = t
            t = self.par[t]
            self.par[tmp] = r
        
        return r
    
    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        
        if rx==ry:
            return
        
        if self.rank[rx]<=self.rank[ry]:
            self.par[ry] += self.par[rx]
            self.par[rx] = ry
            
            if self.rank[rx]==self.rank[ry]:
                self.rank[ry] += 1
                
            for v in self.comp[rx]:
                self.vp[v] = self.rp[rx]+self.vp[v]-self.rp[ry]
                self.comp[ry].append(v)
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
            
            for v in self.comp[ry]:
                self.vp[v] = self.rp[ry]+self.vp[v]-self.rp[rx]
                self.comp[rx].append(v)
                
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]
    
    def add(self, x, y):
        self.rp[self.root(x)] += y
    
    def query(self, x):
        return self.rp[self.root(x)]+self.vp[x]
    
N, Q = map(int, input().split())
uf = Unionfind(N)

for _ in range(Q):
    T, A, B = map(int, input().split())
    
    if T==1:
        uf.unite(A-1, B-1)
    elif T==2:
        uf.add(A-1, B)
    else:
        print(uf.query(A-1))
0