結果

問題 No.556 仁義なきサルたち
ユーザー matsukin1111matsukin1111
提出日時 2019-05-03 11:47:02
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 19 ms / 2,000 ms
コード長 1,784 bytes
コンパイル時間 950 ms
コンパイル使用メモリ 100,356 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-30 05:44:23
合計ジャッジ時間 2,519 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include<iostream>
#include<cstdio>
#include<cstring>
#include <cstdlib>  
#include <math.h>
#include <cmath>   
#include<cctype>
#include<string>
#include<set>
#include<iomanip>
#include <map>
#include<algorithm>
#include <functional>
#include<vector>
#include<climits>
#include<stack>
#include<queue>
#include <deque>
#include <climits>
#include <typeinfo>
#include <utility> 
#define all(x) (x).begin(),(x).end()
#define rep(i,m,n) for(int i = m;i < n;++i)
#define pb push_back
#define fore(i,a) for(auto &i:a)
#define rrep(i,m,n) for(int i = m;i >= n;--i)
#define INF INT_MAX/2
using namespace std;
using ll = long long;
using R = double;
using Data = pair<ll, vector<int>>;
const ll MOD = 1e9 + 7;
const ll inf = 1LL << 50;
struct edge { ll from; ll to; ll cost; };


class UnionFind {
public:
	vector<int> s, p;

	UnionFind() {}
	UnionFind(int size) {
		p.resize(size, 0);
		s.resize(size, 0);
		rep(i, 0, size)makeSet(i);
	}

	void makeSet(int x) {
		p[x] = x;
		s[x] = 1;
	}

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

	void unite(int x, int y) {
		x = findSet(x);
		y = findSet(y);

		if (x == y)return;

		if (s[x] < s[y])swap(x, y);

		p[y] = x;
		s[x] += s[y];
	}


	int findSet(int x) {
		if (x == p[x]) {
			return x;
		}
		else {
			return p[x] = findSet(p[x]);
		}
	}

	int size(int x) {
		return s[findSet(x)];
	}
};

int main() {
	int n, m;
	cin >> n >> m;
	UnionFind un = UnionFind(n);
	
	rep(i, 0, m) {
		int a, b;
		cin >> a >> b;
		a--, b--;
		if (un.same(a, b)) { continue; }
		else{
			if (un.size(a) == un.size(b)) {
				int tempa = un.findSet(a);
				int tempb = un.findSet(b);
				if (tempa > tempb)swap(a,b);
				un.unite(a,b);
			}
			else un.unite(a, b);
		}
	}

	rep(i, 0, n) {
		cout << un.findSet(i)+1 << endl;
	}


	return 0;
}
0