結果

問題 No.1054 Union add query
ユーザー 👑 H20H20
提出日時 2021-10-06 10:36:21
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 522 ms / 2,000 ms
コード長 1,834 bytes
コンパイル時間 338 ms
コンパイル使用メモリ 86,928 KB
実行使用メモリ 92,544 KB
最終ジャッジ日時 2023-09-30 08:39:50
合計ジャッジ時間 4,855 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 96 ms
71,420 KB
testcase_01 AC 96 ms
71,700 KB
testcase_02 AC 100 ms
71,592 KB
testcase_03 AC 522 ms
84,584 KB
testcase_04 AC 447 ms
92,544 KB
testcase_05 AC 459 ms
82,944 KB
testcase_06 AC 310 ms
83,168 KB
testcase_07 AC 263 ms
83,044 KB
testcase_08 AC 299 ms
83,012 KB
testcase_09 AC 344 ms
92,040 KB
testcase_10 AC 208 ms
89,228 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

from collections import defaultdict

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

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            if P[x]!=self.parents[x]:
                L[x]=L[P[x]]+L[x]
                P[x]=self.parents[x]            
            return self.parents[x]

    def union(self, 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.parents[y] = x
        P[y]=x
        L[y]=L[x]-L[y]

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        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):
        group_members = defaultdict(list)
        for member in range(self.n):
            group_members[self.find(member)].append(member)
        return group_members

    def __str__(self):
        return '\n'.join(f'{r}: {m}' for r, m in self.all_group_members().items())

N,Q = map(int,input().split())
uf = UnionFind(N+1)
L = [0]*(N+1)
P = [-1]*(N+1)

for _ in range(Q):
    t,a,b = map(int,input().split())
    if t==1:
        uf.union(a,b)
    if t==2:
        p = uf.find(a)
        L[p]+=b
    if t==3:
        p = uf.find(a)
        if p==a:
            print(L[a])
        else:
            print(L[p]-L[a])
0