結果

問題 No.1054 Union add query
ユーザー WSKRWSKR
提出日時 2020-09-23 23:30:21
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 879 ms / 2,000 ms
コード長 2,132 bytes
コンパイル時間 278 ms
コンパイル使用メモリ 87,336 KB
実行使用メモリ 195,988 KB
最終ジャッジ日時 2023-09-10 13:11:16
合計ジャッジ時間 7,031 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 70 ms
71,400 KB
testcase_01 AC 70 ms
71,272 KB
testcase_02 AC 72 ms
71,432 KB
testcase_03 AC 803 ms
154,044 KB
testcase_04 AC 879 ms
195,988 KB
testcase_05 AC 690 ms
145,504 KB
testcase_06 AC 507 ms
169,432 KB
testcase_07 AC 475 ms
169,428 KB
testcase_08 AC 498 ms
169,360 KB
testcase_09 AC 607 ms
186,944 KB
testcase_10 AC 466 ms
185,224 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#union and query
import sys


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

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(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

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

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


input = sys.stdin.readline


def main():
    N, Q = map(int, input().split())
    Uni = UnionFind(N)
    members = [[i] for i in range(N+1)]
    root_weight = [0 for i in range(N+1)]
    node_weight = [0 for i in range(N+1)]
    command = [tuple(map(int, input().split())) for i in range(Q)]

    for demand, a, b in command:
        if demand == 1:
            #unite
            if Uni.same(a, b):
                pass
            else:
                A, B = Uni.find(a), Uni.find(b)
                x, y = Uni.size(A), Uni.size(B)
                Uni.union(A, B)
                if Uni.find(A) == A:
                    # A's member was bigger
                    #merging
                    assert x >= y
                    for x in members[B]:
                        members[A].append(x)

                    for node in members[B]:
                        node_weight[node] += root_weight[B] - root_weight[A]

                else:
                    assert x <= y
                    for x in members[A]:
                        members[B].append(x)

                    for node in members[A]:
                        node_weight[node] += root_weight[A] - root_weight[B]

        elif demand == 2:
            A = Uni.find(a)
            root_weight[A] += b

        else:
            A = Uni.find(a)
            print(root_weight[A] + node_weight[a])

    return


if __name__ == "__main__":
    main()

0