結果

問題 No.556 仁義なきサルたち
ユーザー DenteDente
提出日時 2019-09-10 17:11:32
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 20 ms / 2,000 ms
コード長 1,344 bytes
コンパイル時間 1,661 ms
コンパイル使用メモリ 169,312 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-15 13:06:21
合計ジャッジ時間 3,035 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,380 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 2 ms
4,380 KB
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 2 ms
4,376 KB
testcase_09 AC 3 ms
4,380 KB
testcase_10 AC 3 ms
4,380 KB
testcase_11 AC 3 ms
4,376 KB
testcase_12 AC 4 ms
4,380 KB
testcase_13 AC 8 ms
4,376 KB
testcase_14 AC 10 ms
4,376 KB
testcase_15 AC 10 ms
4,376 KB
testcase_16 AC 16 ms
4,380 KB
testcase_17 AC 17 ms
4,380 KB
testcase_18 AC 19 ms
4,380 KB
testcase_19 AC 18 ms
4,376 KB
testcase_20 AC 19 ms
4,376 KB
testcase_21 AC 20 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
#define REP(i,a) for(int i = 0; i < (a); i++)
#define ALL(a) (a).begin(),(a).end()
typedef long long ll;
typedef pair<int, int> P;
const int INF = 1e9;
const int MOD = 1e9 + 7;

struct UnionFind{
    vector<int> par;
    vector<int> siz;

    UnionFind(int n){
        init(n);
    }

    //n要素で初期化
    void init(int n){
        par.resize(n);
        siz.resize(n);
        for(int i = 0; i < n; i++){
            par[i] = i;
            siz[i] = 1;
        }
    }

    //木の根を求める
    int root(int x){
        if(par[x] == x) return x;
        else return par[x] = root(par[x]);
    }

    //xとyの属する集合を併合
    void unite(int x, int y){
        x = root(x);
        y = root(y);
        if(x == y) return;
        if(siz[x] < siz[y]) swap(x, y);
        siz[x] += siz[y];
        par[y] = x;
    }

    bool same(int x, int y){
        return root(x) == root(y);
    }

    int size(int x){
        return siz[root(x)];
    }
};

signed main(){
    int n,m;
    cin >> n >> m;
    UnionFind uf(n);
    int a,b;
    REP(i,m){
        cin >> a >> b;
        a--;
        b--;
        if(uf.root(a) > uf.root(b)){
            swap(a,b);
        }
        uf.unite(uf.root(a), uf.root(b));
    }
    REP(i,n){
        cout << uf.root(i) + 1 << endl;
    }
}
0