結果

問題 No.317 辺の追加
ユーザー matsu7874matsu7874
提出日時 2015-12-10 00:53:12
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,530 bytes
コンパイル時間 204 ms
コンパイル使用メモリ 10,872 KB
実行使用メモリ 15,036 KB
最終ジャッジ日時 2023-10-13 09:54:25
合計ジャッジ時間 4,194 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,264 KB
testcase_01 AC 16 ms
8,040 KB
testcase_02 TLE -
testcase_03 -- -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:

    def __init__(self, size):
        # 負の値はルート (集合の代表) で集合の個数
        # 正の値は次の要素を表す
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        # 集合の代表を求める
        while self.table[x] >= 0:
            x = self.table[x]
        return x

    def union(self, x, y):
        # 併合
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] >= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
        return self.table[s1]


N, M = map(int, input().split())
uf = UnionFind(N)
for i in range(M):
    u, v = map(int, input().split())
    uf.union(u - 1, v - 1)
connected = {}
for i in range(N):
    g = uf.find(i)
    if g in connected:
        connected[g] += 1
    else:
        connected[g] = 1
size = [v for k, v in connected.items()]
S = len(size)
dp = [[10**10 for j in range(S)] for i in range(N + 1)]

for i in range(S):
    dp[0][i] = 0
for i in range(S):
    dp[size[i]][i] = 0

for i in range(1, S):
    for j in range(0, N + 1):
        dp[j][i] = min(dp[j][i], dp[j][i - 1])
        if j >= size[i]:
            dp[j][i] = min(dp[j][i], dp[j - size[i]][i - 1] + 1)

for i in range(1, N + 1):
    if min(dp[i]) == 10**10:
        print(-1)
    else:
        print(min(dp[i]))

# for x in dp:
#     print(x)
0