結果

問題 No.1054 Union add query
ユーザー 37zigen37zigen
提出日時 2019-11-09 03:50:00
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,562 bytes
コンパイル時間 100 ms
コンパイル使用メモリ 11,040 KB
実行使用メモリ 37,464 KB
最終ジャッジ日時 2023-08-18 17:17:46
合計ジャッジ時間 6,257 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 115 ms
29,656 KB
testcase_01 AC 117 ms
29,740 KB
testcase_02 AC 117 ms
29,660 KB
testcase_03 TLE -
testcase_04 TLE -
testcase_05 TLE -
testcase_06 TLE -
testcase_07 TLE -
testcase_08 TLE -
testcase_09 TLE -
testcase_10 AC 1,482 ms
37,464 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import numpy as np

class DJSet():
    
    def __init__(self, n):
        self.upper = np.empty((n), int)
        self.weight = np.empty((n), int)
        for i in range(n):
            self.upper[i] = -1
            self.weight[i] = 0

    def equiv(self, x, y):
        return self.root(x) == self.root(y)

    def root(self, x):
        if self.upper[x] < 0:
            return x
        else:
            return self.root(self.upper[x])

    def get_weight(self, x):
        if self.upper[x] < 0:
            return self.weight[x]
        else:
            return self.weight[x] + self.get_weight(self.upper[x])
    def setUnion(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        if self.upper[x] < self.upper[y]:
            x ^= y
            y ^= x
            x ^= y
        self.upper[y] = self.upper[y] + self.upper[x]
        self.upper[x] = y
        self.weight[x] = self.weight[x] - self.weight[y]

    def add_weight(self, x, w):
        x = self.root(x)
        self.weight[x] = self.weight[x] + w
        
def run():
    N, Q = input().split(" ")
    N = int(N)
    Q = int(Q)
    ds = DJSet(N)
    for q in range(Q):
        T, A, B = input().split(" ")
        T = int(T)
        A = int(A)
        B = int(B)
        A = A - 1
        if (T == 1):
            B = B - 1
            if (ds.equiv(A, B)):
                continue
            ds.setUnion(A, B)
        elif (T == 2):
            ds.add_weight(A, B)
        elif (T == 3):
            print(ds.get_weight(A))
    
run()
0