結果

問題 No.317 辺の追加
ユーザー face4face4
提出日時 2019-11-16 17:15:19
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 245 ms / 2,000 ms
コード長 1,407 bytes
コンパイル時間 889 ms
コンパイル使用メモリ 84,828 KB
実行使用メモリ 4,876 KB
最終ジャッジ日時 2023-10-25 05:40:03
合計ジャッジ時間 10,868 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,348 KB
testcase_01 AC 2 ms
4,348 KB
testcase_02 AC 161 ms
4,348 KB
testcase_03 AC 165 ms
4,348 KB
testcase_04 AC 162 ms
4,348 KB
testcase_05 AC 148 ms
4,348 KB
testcase_06 AC 192 ms
4,348 KB
testcase_07 AC 61 ms
4,348 KB
testcase_08 AC 184 ms
4,348 KB
testcase_09 AC 202 ms
4,348 KB
testcase_10 AC 242 ms
4,348 KB
testcase_11 AC 141 ms
4,348 KB
testcase_12 AC 242 ms
4,348 KB
testcase_13 AC 152 ms
4,348 KB
testcase_14 AC 218 ms
4,348 KB
testcase_15 AC 234 ms
4,348 KB
testcase_16 AC 186 ms
4,348 KB
testcase_17 AC 224 ms
4,348 KB
testcase_18 AC 241 ms
4,348 KB
testcase_19 AC 245 ms
4,348 KB
testcase_20 AC 184 ms
4,348 KB
testcase_21 AC 95 ms
4,348 KB
testcase_22 AC 52 ms
4,348 KB
testcase_23 AC 53 ms
4,348 KB
testcase_24 AC 165 ms
4,876 KB
testcase_25 AC 117 ms
4,612 KB
testcase_26 AC 124 ms
4,612 KB
testcase_27 AC 102 ms
4,348 KB
testcase_28 AC 53 ms
4,348 KB
testcase_29 AC 13 ms
4,348 KB
testcase_30 AC 213 ms
4,612 KB
testcase_31 AC 208 ms
4,612 KB
testcase_32 AC 211 ms
4,612 KB
testcase_33 AC 209 ms
4,612 KB
testcase_34 AC 209 ms
4,612 KB
testcase_35 AC 208 ms
4,612 KB
testcase_36 AC 209 ms
4,612 KB
testcase_37 AC 209 ms
4,612 KB
testcase_38 AC 214 ms
4,348 KB
testcase_39 AC 209 ms
4,612 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<map>
using namespace std;

// 簡易UF
struct UF{
    vector<int> p;
    int n;

    UF(int siz){
        n = siz;
        p.resize(n, 0);
        for(int i = 0; i < n; i++)  p[i] = i;
    }

    int parent(int x){
        if(p[x] != x)   p[x] = parent(p[x]);
        return p[x];
    }

    bool same(int x, int y){
        return parent(x) == parent(y);
    }
    
    void unite(int x, int y){
        x = parent(x), y = parent(y);
        p[x] = y;
    }
};

// ナップサックで同じものをN個まで選べるときに
// 2進数を使ってlog(N)で0~N個選ぶ場合を網羅するテク
int main(){
    int n, x;
    cin >> n >> x;
    UF uf(n);
    while(x-- > 0){
        int u, v;
        cin >> u >> v;
        uf.unite(--u, --v);
    }
    vector<int> cnt(n, 0);
    for(int i = 0; i < n; i++)  cnt[uf.parent(i)]++;
    map<int,int> m;
    for(int i = 0; i < n; i++){
        if(cnt[i])  m[cnt[i]]++;
    }
    vector<int> dp(n+1, 1<<30);
    dp[0] = 0;
    for(auto p : m){
        int res = p.second;
        for(int k = 0; res > 0; k++){
            int take = min(1<<k, res);
            res -= take;
            for(int j = n; j >= p.first*take; j--){
                dp[j] = min(dp[j], dp[j-p.first*take]+take);
            }
        }
    }
    for(int i = 1; i <= n; i++) cout << (dp[i]==1<<30 ? -1 : dp[i]-1) << endl;
    return 0;
}
0