結果

問題 No.556 仁義なきサルたち
ユーザー gzlcpgzlcp
提出日時 2017-08-11 22:45:43
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 19 ms / 2,000 ms
コード長 1,370 bytes
コンパイル時間 875 ms
コンパイル使用メモリ 98,344 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-02 23:13:05
合計ジャッジ時間 2,014 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ(β)

テストケース

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

ソースコード

diff #

#include<iostream>
#include<iomanip>
#include<math.h>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<complex>

#define INF (long long)1000000000
#define MOD 1000000007
#define EPS 1e-8

#define REP(i, m) for(long long i = 0; i < m; ++i)
#define FOR(i, n, m) for(long long i = n; i < m; ++i)
#define ALL(v) v.begin(), v.end()
#define pb push_back

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef long double ld;

class union_find {
public:
	union_find(int n)
	: par_(n, -1)
	{}
	void init(int n) {
		par_.assign(n, -1);
	}

	int root(int x) {
		return par_[x] < 0 ? x : par_[x] = root(par_[x]);
	}

	bool unite(int x, int y) {
		x = root(x); y = root(y);
		if(x == y) {
			return false;
		} else {
				par_[x] += par_[y];
				par_[y] = x;
			return true;
		}
	}

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

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

private:
	std::vector<int> par_;
};

int main() {
	int n,m;
	cin>>n>>m;
	union_find uf(n);
	REP(i,m) {
		int a, b;
		cin>>a>>b;
		--a;
		--b;
		if(uf.same(a,b)) continue;
		if(uf.size(a)>uf.size(b)) {
			uf.unite(a,b);
		} else if(uf.size(b)>uf.size(a)) {
			uf.unite(b,a);
		} else {
			if(uf.root(a)<uf.root(b)) uf.unite(a,b);
			else uf.unite(b,a);
		}
	}
	REP(i,n) cout<<uf.root(i)+1<<endl;
}
0