結果

問題 No.1054 Union add query
ユーザー terasaterasa
提出日時 2022-05-26 02:07:29
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 932 ms / 2,000 ms
コード長 2,097 bytes
コンパイル時間 562 ms
コンパイル使用メモリ 81,756 KB
実行使用メモリ 146,292 KB
最終ジャッジ日時 2023-10-20 19:20:34
合計ジャッジ時間 6,454 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 45 ms
55,700 KB
testcase_01 AC 46 ms
55,700 KB
testcase_02 AC 45 ms
55,700 KB
testcase_03 AC 695 ms
102,736 KB
testcase_04 AC 932 ms
146,292 KB
testcase_05 AC 562 ms
91,440 KB
testcase_06 AC 514 ms
113,452 KB
testcase_07 AC 457 ms
113,280 KB
testcase_08 AC 478 ms
112,920 KB
testcase_09 AC 566 ms
137,604 KB
testcase_10 AC 284 ms
129,676 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
import pypyjit
import itertools
import heapq
import math
from collections import deque, defaultdict, Counter
import bisect

input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
pypyjit.set_param('max_unroll_recursion=-1')


class UnionFind:
    def __init__(self, N):
        self.N = N
        self.par = [-1] * N
        self.members = [[i] for i in range(N)]
        self.value = [0] * N
        self.lazy = [0] * N

    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return False
        if x > y:
            x, y = y, x

        for i in self.members[y]:
            self.value[i] += self.lazy[y] - self.lazy[x]
        self.lazy[y] = 0

        self.par[x] += self.par[y]
        self.par[y] = x
        self.members[x] += self.members[y]
        return True

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

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

    def roots(self):
        return [i for i in range(self.N) if self.par[i] < 0]


def index_lt(a, x):
    'return largest index s.t. A[i] < x or -1 if it does not exist'
    return bisect.bisect_left(a, x) - 1


def index_le(a, x):
    'return largest index s.t. A[i] <= x or -1 if it does not exist'
    return bisect.bisect_right(a, x) - 1


def index_gt(a, x):
    'return smallest index s.t. A[i] > x or len(a) if it does not exist'
    return bisect.bisect_right(a, x)


def index_ge(a, x):
    'return smallest index s.t. A[i] >= x or len(a) if it does not exist'
    return bisect.bisect_left(a, x)


N, Q = map(int, input().split())
uf = UnionFind(N)
for _ in range(Q):
    t, a, b = map(int, input().split())
    if t == 1:
        a -= 1
        b -= 1
        uf.unite(a, b)
    elif t == 2:
        a -= 1
        p = uf.find(a)
        uf.lazy[p] += b
    else:
        a -= 1
        p = uf.find(a)
        print(uf.value[a] + uf.lazy[p])
0