結果

問題 No.1054 Union add query
ユーザー 👑 tamatotamato
提出日時 2020-05-15 22:06:35
言語 PyPy3
(7.3.13)
結果
AC  
実行時間 394 ms / 2,000 ms
コード長 1,699 bytes
コンパイル時間 238 ms
コンパイル使用メモリ 82,044 KB
実行使用メモリ 102,864 KB
最終ジャッジ日時 2023-10-19 14:30:49
合計ジャッジ時間 4,000 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 36 ms
53,504 KB
testcase_01 AC 36 ms
53,504 KB
testcase_02 AC 36 ms
53,504 KB
testcase_03 AC 394 ms
94,196 KB
testcase_04 AC 366 ms
100,564 KB
testcase_05 AC 365 ms
93,920 KB
testcase_06 AC 259 ms
91,552 KB
testcase_07 AC 211 ms
91,560 KB
testcase_08 AC 250 ms
87,316 KB
testcase_09 AC 263 ms
102,864 KB
testcase_10 AC 128 ms
86,876 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.buffer.readline

    class UnionFind():
        def __init__(self, n):
            self.n = n
            self.root = [-1] * (n + 1)
            self.val = [0] * (n+1)
            self.rnk = [0] * (n + 1)

        def find_root(self, x):
            while self.root[x] >= 0:
                x = self.root[x]
            return x

        def unite(self, x, y):
            x = self.find_root(x)
            y = self.find_root(y)
            if x == y:
                return
            elif self.rnk[x] > self.rnk[y]:
                self.root[x] += self.root[y]
                self.root[y] = x
                self.val[y] -= self.val[x]
            else:
                self.root[y] += self.root[x]
                self.root[x] = y
                self.val[x] -= self.val[y]
                if self.rnk[x] == self.rnk[y]:
                    self.rnk[y] += 1

        def isSameGroup(self, x, y):
            return self.find_root(x) == self.find_root(y)

        def size(self, x):
            return -self.root[self.find_root(x)]

    N, Q = map(int, input().split())
    UF = UnionFind(N+1)
    ans = []
    ans_append = ans.append
    for _ in range(Q):
        t, a, b = map(int, input().split())
        if t == 1:
            UF.unite(a, b)
        elif t == 2:
            x = UF.find_root(a)
            UF.val[x] += b
        else:
            tmp = 0
            x = a
            while True:
                tmp += UF.val[x]
                x = UF.root[x]
                if x < 0:
                    break
            ans.append(tmp)
    print(*ans, sep="\n")


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