結果

問題 No.556 仁義なきサルたち
ユーザー titiatitia
提出日時 2024-04-01 01:51:25
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 68 ms / 2,000 ms
コード長 953 bytes
コンパイル時間 166 ms
コンパイル使用メモリ 11,904 KB
実行使用メモリ 11,264 KB
最終ジャッジ日時 2024-04-01 01:51:28
合計ジャッジ時間 2,516 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 29 ms
9,984 KB
testcase_01 AC 31 ms
9,984 KB
testcase_02 AC 31 ms
9,984 KB
testcase_03 AC 29 ms
9,984 KB
testcase_04 AC 29 ms
9,984 KB
testcase_05 AC 29 ms
9,984 KB
testcase_06 AC 29 ms
9,984 KB
testcase_07 AC 29 ms
9,984 KB
testcase_08 AC 30 ms
9,984 KB
testcase_09 AC 30 ms
10,112 KB
testcase_10 AC 31 ms
10,112 KB
testcase_11 AC 35 ms
10,112 KB
testcase_12 AC 32 ms
10,112 KB
testcase_13 AC 34 ms
10,624 KB
testcase_14 AC 57 ms
10,624 KB
testcase_15 AC 47 ms
10,624 KB
testcase_16 AC 47 ms
11,008 KB
testcase_17 AC 55 ms
11,008 KB
testcase_18 AC 68 ms
11,008 KB
testcase_19 AC 66 ms
10,880 KB
testcase_20 AC 65 ms
11,264 KB
testcase_21 AC 65 ms
11,008 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
input = sys.stdin.readline

N,M=map(int,input().split())

# UnionFind

Group = [i for i in range(N+1)] # グループ分け
Nodes = [1]*(N+1) # 各グループのノードの数
ANS=[i for i in range(N+1)]

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

def Union(x,y):
    if find(x) != find(y):
        if Nodes[find(x)] < Nodes[find(y)]:
            
            Nodes[find(y)] += Nodes[find(x)]
            Nodes[find(x)] = 0
            Group[find(x)] = find(y)
            
        else:
            Nodes[find(x)] += Nodes[find(y)]
            Nodes[find(y)] = 0
            Group[find(y)] = find(x)

for i in range(M):
    a,b=map(int,input().split())

    x=Nodes[find(a)]
    y=Nodes[find(b)]

    if x<y:
        MIN=ANS[find(b)]
    elif x>y:
        MIN=ANS[find(a)]
    else:
        MIN=min(ANS[find(a)],ANS[find(b)])

    Union(a,b)
    ANS[find(a)]=MIN

for i in range(1,N+1):
    print(ANS[find(i)])
0