結果

問題 No.556 仁義なきサルたち
ユーザー roarisroaris
提出日時 2019-08-16 11:38:19
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 151 ms / 2,000 ms
コード長 890 bytes
コンパイル時間 857 ms
コンパイル使用メモリ 81,736 KB
実行使用メモリ 76,744 KB
最終ジャッジ日時 2023-10-22 00:18:15
合計ジャッジ時間 3,485 ms
ジャッジサーバーID
(参考情報)
judge14 / judge10
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 38 ms
53,408 KB
testcase_01 AC 38 ms
53,408 KB
testcase_02 AC 38 ms
53,408 KB
testcase_03 AC 40 ms
53,408 KB
testcase_04 AC 39 ms
53,408 KB
testcase_05 AC 40 ms
53,408 KB
testcase_06 AC 41 ms
53,408 KB
testcase_07 AC 41 ms
53,408 KB
testcase_08 AC 43 ms
53,408 KB
testcase_09 AC 50 ms
61,112 KB
testcase_10 AC 56 ms
65,492 KB
testcase_11 AC 62 ms
67,924 KB
testcase_12 AC 62 ms
67,924 KB
testcase_13 AC 58 ms
66,272 KB
testcase_14 AC 102 ms
76,076 KB
testcase_15 AC 116 ms
76,680 KB
testcase_16 AC 92 ms
76,048 KB
testcase_17 AC 124 ms
76,744 KB
testcase_18 AC 151 ms
76,584 KB
testcase_19 AC 84 ms
75,992 KB
testcase_20 AC 85 ms
75,992 KB
testcase_21 AC 85 ms
75,996 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class Unionfind:
    def __init__(self, N):
        self.par = [-1] * N
    
    def root(self, x):
        if self.par[x] < 0:
            return x
        
        self.par[x] = self.root(self.par[x])
        return self.par[x]
    
    def unite(self, x, y):
        rx, ry = self.root(x), self.root(y)
        
        if rx != ry:
            rx_num, ry_num = -self.par[rx], -self.par[ry]
            
            if rx_num > ry_num or (rx_num == ry_num and rx < ry):
                self.par[rx] += self.par[ry]
                self.par[ry] = rx
            elif ry_num > rx_num or (rx_num == ry_num and ry < rx):
                self.par[ry] += self.par[rx]
                self.par[rx] = ry
            
N, M = map(int, input().split())
uf = Unionfind(N)

for _ in range(M):
    Ai, Bi = map(int, input().split())
    uf.unite(Ai-1, Bi-1)

for i in range(N):
    print(uf.root(i)+1)
0