結果

問題 No.317 辺の追加
コンテスト
ユーザー titia
提出日時 2023-09-20 00:15:34
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 266 ms / 2,000 ms
コード長 1,258 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 488 ms
コンパイル使用メモリ 84,736 KB
実行使用メモリ 89,984 KB
最終ジャッジ日時 2026-03-27 07:50:10
合計ジャッジ時間 9,582 ms
ジャッジサーバーID
(参考情報)
judge2_1 / judge1_1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 38
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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