結果

問題 No.556 仁義なきサルたち
ユーザー misora192misora192
提出日時 2020-07-14 23:32:43
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 4 ms / 2,000 ms
コード長 1,430 bytes
コンパイル時間 1,607 ms
コンパイル使用メモリ 169,268 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-12 06:29:11
合計ジャッジ時間 3,141 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <bits/stdc++.h>
#define rep(i,n) for(int i=(0);i<(n);i++)

using namespace std;

typedef long long ll;

template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

// union-find tree with size(struct)
struct UnionFind{
    vector<int> par; // 親ノード
	vector<int> size; // 連結成分のサイズ

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

    void init(int n = 1) {
        par.resize(n);
		size.resize(n);
        for (int i = 0; i < n; ++i){
			par[i] = i;
			size[i] = 1;
		}
    }

    int find(int x) {
        if (par[x] == x)  return x;

        int r = find(par[x]);
        return par[x] = r;
    }

    bool issame(int x, int y) {
        return find(x) == find(y);
    }

    bool unite(int x, int y) {
	    x = find(x);
		y = find(y);
	    if (x == y) return false;

		int sx = getSize(x);
		int sy = getSize(y);

	    if (sx > sy || (sx == sy && x < y)){
			par[y] = x;
			size[x] += size[y];
		}else{
			par[x] = y;
			size[y] += size[x];
		}
	    return true;
    }

	int getSize(int x){
		return size[find(x)];
	}
};


int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);

	int n, m;
	cin >> n >> m;

	UnionFind uf(n);
	rep(i, m){
		int a, b;
		cin >> a >> b;
		a--; b--;

		if(!uf.issame(a, b)) uf.unite(a, b);
	}
	
	rep(i, n){
		cout << uf.find(i) + 1 << "\n";
	}
}
0