結果

問題 No.1054 Union add query
ユーザー hedwig100hedwig100
提出日時 2020-05-15 23:44:47
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
WA  
実行時間 -
コード長 2,360 bytes
コンパイル時間 120 ms
コンパイル使用メモリ 12,188 KB
実行使用メモリ 30,876 KB
最終ジャッジ日時 2023-10-19 17:58:41
合計ジャッジ時間 9,194 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 30 ms
10,460 KB
testcase_01 WA -
testcase_02 AC 30 ms
10,368 KB
testcase_03 TLE -
testcase_04 TLE -
testcase_05 TLE -
testcase_06 TLE -
testcase_07 AC 1,929 ms
15,068 KB
testcase_08 AC 1,824 ms
15,068 KB
testcase_09 TLE -
testcase_10 AC 1,325 ms
21,992 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
sys.setrecursionlimit(100000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

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

    def find(self,x): #根を見つける、繋ぎ直す
        if self.parents[x] < 0:
            return x
        else:
            p = self.find(self.parents[x])
            self.lazy[x] += self.lazy[self.parents[x]]
            self.parents[x] = p
            return p
    
    def unite(self,x,y): #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.lazy[y] = -self.count[x]
        self.parents[y] = x
    
    def same(self,x,y):#xとyが同じグループにいるか判定
        return self.find(x) == self.find(y)
    
    def members(self,x):#xと同じグループのメンバーを列挙
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def size(self,x):#xが属するグループのメンバーの数
        return -self.parents[self.find(x)]
    
    def roots(self):#ufの根を列挙
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):#グループの数を数える
        return len(self.roots())

    def all_group_members(self):#根:メンバの辞書を返す
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):#print()での表示用
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
    
    def add(self,x,b):
        x = self.find(x)
        self.count[x] += b
    
    def calc(self,x):
        if self.parents[x] < 0:
            return self.count[x]
        self.find(x)
        return self.count[x] + self.count[self.parents[x]] + self.lazy[x]


def main():  
    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
            uf.add(a,b)
        else:
            a -= 1
            print(uf.calc(a))
if __name__ == '__main__':
    main()
0