結果

問題 No.1054 Union add query
ユーザー uni_pythonuni_python
提出日時 2020-05-16 19:42:20
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 622 ms / 2,000 ms
コード長 2,306 bytes
コンパイル時間 404 ms
コンパイル使用メモリ 81,876 KB
実行使用メモリ 86,340 KB
最終ジャッジ日時 2023-10-23 23:10:54
合計ジャッジ時間 4,412 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 35 ms
53,452 KB
testcase_01 AC 35 ms
53,452 KB
testcase_02 AC 34 ms
53,452 KB
testcase_03 AC 622 ms
83,024 KB
testcase_04 AC 348 ms
86,340 KB
testcase_05 AC 484 ms
80,796 KB
testcase_06 AC 214 ms
79,188 KB
testcase_07 AC 188 ms
79,240 KB
testcase_08 AC 207 ms
79,180 KB
testcase_09 AC 254 ms
85,644 KB
testcase_10 AC 148 ms
83,104 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input=sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
mod=10**9+7

################
class UnionFind():
    def __init__(self,n):
        self.n = n
        self.parents = [-1]*n
        self.count = [0] * n

    def find(self,x): #根を見つける、繋ぎ直す
        if self.parents[x] < 0:
            return x
        else:
            p = self.find(self.parents[x])
            return p
    
    def unite(self,x,y): #x,yの含むグループを併合する
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return
        
        if self.parents[x] > self.parents[y]:
            x,y = y,x

        self.parents[x] += self.parents[y]
        self.count[y] -= self.count[x]
        self.parents[y] = x
    
    def same(self,x,y):#xとyが同じグループにいるか判定
        return self.find(x) == self.find(y)
    
    def members(self,x):#xと同じグループのメンバーを列挙
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def size(self,x):#xが属するグループのメンバーの数
        return -self.parents[self.find(x)]
    
    def roots(self):#ufの根を列挙
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):#グループの数を数える
        return len(self.roots())

    def all_group_members(self):#根:メンバの辞書を返す
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):#print()での表示用
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
    
    def add(self,x,b):
        x = self.find(x)
        self.count[x] += b
    
    def calc(self,x):
        if self.parents[x] < 0:
            return self.count[x]
        ans = self.calc(self.parents[x])
        return ans + self.count[x]
    
################
def main():

    N,Q=MI()
    uf=UnionFind(N)

    
    for _ in range(Q):
        t,a,b=MI()
        if t==1:
            a-=1
            b-=1
            uf.unite(a,b)
        elif t==2:
            a-=1
            uf.add(a,b)
        else:
            a-=1
            print(uf.calc(a))

if __name__=="__main__":
    main()
0