結果

問題 No.317 辺の追加
ユーザー titia
提出日時 2023-09-20 00:15:34
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 386 ms / 2,000 ms
コード長 1,258 bytes
コンパイル時間 193 ms
コンパイル使用メモリ 81,792 KB
実行使用メモリ 84,224 KB
最終ジャッジ日時 2024-07-05 21:51:02
合計ジャッジ時間 11,945 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #

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

from collections import Counter

# UnionFind

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

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):
    x,y=map(int,input().split())
    x-=1
    y-=1
    Union(x,y)

LIST=[]

for i in range(N):
    if find(i)==i:
        LIST.append(Nodes[i])

C=Counter(LIST)

DP=[1<<30]*(N+1)
DP[0]=0

for l in C:
    c=C[l]

    LL=[]

    for j in range(30):
        if c>2**j:
            LL.append(2**j)
            c-=2**j
        else:
            LL.append(c)
            break

    #print(c,LL)

    for x in LL:
        for j in range(N-x*l,-1,-1):
            if DP[j]!=1<<30:
                DP[j+x*l]=min(DP[j+x*l],DP[j]+x)

    #print(DP)

for i in range(1,N+1):
    if DP[i]==1<<30:
        print(-1)
    else:
        print(DP[i]-1)
0