結果

問題 No.1054 Union add query
ユーザー convexineqconvexineq
提出日時 2021-02-08 15:55:55
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 474 ms / 2,000 ms
コード長 1,590 bytes
コンパイル時間 1,015 ms
コンパイル使用メモリ 86,804 KB
実行使用メモリ 92,256 KB
最終ジャッジ日時 2023-09-19 06:05:10
合計ジャッジ時間 8,071 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 76 ms
70,952 KB
testcase_01 AC 79 ms
71,264 KB
testcase_02 AC 77 ms
71,308 KB
testcase_03 AC 474 ms
82,844 KB
testcase_04 AC 420 ms
92,256 KB
testcase_05 AC 455 ms
80,992 KB
testcase_06 AC 344 ms
82,992 KB
testcase_07 AC 283 ms
82,804 KB
testcase_08 AC 343 ms
82,820 KB
testcase_09 AC 333 ms
91,120 KB
testcase_10 AC 189 ms
88,660 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n)) #親ノード
        self.size = [1]*n #グループの要素数
        self.lazy = [0]*n
 
    def root(self, x): #root(x): xの根ノードを返す.
        while self.parent[x] != x:
            #self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x 
 
    def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる
        x, y = self.root(x), self.root(y)
        if x == y: return False
        if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように
        self.size[x] += self.size[y] #xの要素数を更新
        self.parent[y] = x #yをxにつなぐ
        self.lazy[y] -= self.lazy[x]
        return True
 
    def issame(self, x, y): #same(x,y): xとyが同じ組ならTrue
        return self.root(x) == self.root(y)
        
    def getsize(self,x): #size(x): xのいるグループの要素数を返す
        return self.size[self.root(x)]

    def add(self,x,b):
        self.lazy[self.root(x)] += b

    def get(self,x):
        v = 0
        while self.parent[x] != x:
            v += self.lazy[x]
            x = self.parent[x]
        return v + self.lazy[x]


        
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline 

n,q = map(int,readline().split())

UF = UnionFind(n)

for _ in range(q):
    t,a,b = map(int,readline().split())
    if t==1:
        UF.merge(a-1,b-1)
    elif t==2:
        UF.add(a-1,b)
    else:
        print(UF.get(a-1))
0