結果

問題 No.1054 Union add query
ユーザー tktk_snsntktk_snsn
提出日時 2021-02-03 23:22:28
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 946 ms / 2,000 ms
コード長 955 bytes
コンパイル時間 1,417 ms
コンパイル使用メモリ 87,048 KB
実行使用メモリ 224,776 KB
最終ジャッジ日時 2023-09-12 18:58:58
合計ジャッジ時間 7,569 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 72 ms
71,356 KB
testcase_01 AC 72 ms
71,216 KB
testcase_02 AC 74 ms
71,220 KB
testcase_03 AC 802 ms
183,452 KB
testcase_04 AC 946 ms
224,776 KB
testcase_05 AC 682 ms
174,872 KB
testcase_06 AC 535 ms
192,796 KB
testcase_07 AC 500 ms
192,844 KB
testcase_08 AC 520 ms
192,476 KB
testcase_09 AC 566 ms
216,020 KB
testcase_10 AC 440 ms
197,260 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

N, Q = map(int, input().split())
query = tuple(tuple(map(int, input().split())) for _ in range(Q))

root = [-1] * N
member = [[i] for i in range(N)]
leader_val = [0] * N
each_val = [0] * N


def find(x):
    if root[x] < 0:
        return x
    root[x] = res = find(root[x])
    return res


def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        return
    # x:big, y:small
    if -root[x] < -root[y]:
        x, y = y, x

    xval = leader_val[x]
    yval = leader_val[y]
    leader_val[y] = 0

    root[x] += root[y]
    root[y] = x
    while member[y]:
        i = member[y].pop()
        each_val[i] += yval - xval
        member[x].append(i)


for t, a, b in query:
    if t == 1:
        unite(a - 1, b - 1)
    elif t == 2:
        x = find(a - 1)
        leader_val[x] += b
    else:
        x = find(a - 1)
        print(leader_val[x] + each_val[a-1])
0