結果

問題 No.1054 Union add query
ユーザー nephrologistnephrologist
提出日時 2020-05-16 09:44:16
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 771 ms / 2,000 ms
コード長 1,343 bytes
コンパイル時間 172 ms
コンパイル使用メモリ 81,488 KB
実行使用メモリ 143,168 KB
最終ジャッジ日時 2023-10-21 22:46:23
合計ジャッジ時間 5,320 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 41 ms
53,324 KB
testcase_01 AC 42 ms
53,324 KB
testcase_02 AC 39 ms
53,324 KB
testcase_03 AC 683 ms
99,056 KB
testcase_04 AC 771 ms
143,168 KB
testcase_05 AC 470 ms
87,904 KB
testcase_06 AC 319 ms
111,656 KB
testcase_07 AC 277 ms
111,624 KB
testcase_08 AC 311 ms
111,648 KB
testcase_09 AC 327 ms
130,016 KB
testcase_10 AC 205 ms
128,368 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

input = sys.stdin.buffer.readline
n, q = map(int, input().split())

# union-findを魔改造
groups = [[i] for i in range(n + 1)]  # groupsには同グループすべての頂点を入れる

par = [-1] * (n + 1)  # parには根か、-sizeが入る
add_edge = [0] * (n + 1)
add_root = [0] * (n + 1)


def find(x):
    if par[x] < 0:
        return x
    else:
        y = par[x]
        par[x] = find(y)
        return par[x]


def size(x):
    return -par[find(x)]


def unite(x, y):
    if find(x) == find(y):
        return False
    X = find(x)
    Y = find(y)
    if size(x) < size(y):  # 必ずyのsizeが小さくする
        x, y = y, x
        X = find(x)
        Y = find(y)
    par[X] += par[Y]
    par[Y] = X
    # 各々の足し算結果の調整
    rx = add_root[X]
    ry = add_root[Y]
    for i in range(len(groups[Y])):
        e = groups[Y][i]
        oldpy = add_edge[e]
        newpy = oldpy + (ry - rx)
        add_edge[e] = newpy
    add_root[Y] = 0
    # group管理の調整
    groups[X].extend(groups[Y])
    groups[Y] = []
    return True


def query(x):
    X = find(x)
    return add_edge[x] + add_root[X]


for _ in range(q):
    t, a, b = map(int, input().split())
    if t == 1:
        unite(a, b)
    elif t == 2:
        X = find(a)
        add_root[X] += b
    else:
        print(query(a))
0