結果

問題 No.556 仁義なきサルたち
ユーザー lapilapi
提出日時 2019-07-03 13:59:05
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 16 ms / 2,000 ms
コード長 2,112 bytes
コンパイル時間 1,008 ms
コンパイル使用メモリ 108,588 KB
実行使用メモリ 4,352 KB
最終ジャッジ日時 2023-10-13 09:01:55
合計ジャッジ時間 2,520 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

diff #

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <numeric>
#include <regex>
#include <tuple>
#include<iomanip>
using namespace std;

typedef long long ll;
typedef pair<int, int> P;
#define MOD 1000000007 // 10^9 + 7
#define INF 1000000000 // 10^9
#define LLINF 1LL<<60

class UF {
private:
	std::vector<int> parent;
	std::vector<int> num_member; // 同じグループに属するメンバーの数
								 // 自身込み

public:
	// コンストラクタ ※注意※ 0~nまでのn+1個を作る
	UF(int n) {
		for (int i = 0; i <= n; i++) {
			parent.push_back(i); //
			num_member.push_back(1);
		}
	}
	// 木の根を求める
	int root(int x) {
		if (parent[x] == x)return x;
		else return parent[x] = root(parent[x]);
	}

	// 同じ集合に属するメンバーの数を求める
	int numOfmember(int x) {
		if (parent[x] == x) return num_member[x];
		else return num_member[x] = numOfmember(parent[x]);
	}

	// xとyの属する集合を合併
	void unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);
		if (rx == ry) return; // 元々合併済みの場合
		if (num_member[rx] < num_member[ry]) {
			num_member[ry] = numOfmember(ry) + numOfmember(rx);
			parent[rx] = ry;
		}
		else if(num_member[rx] > num_member[ry]){
			num_member[rx] = numOfmember(ry) + numOfmember(rx);
			parent[ry] = rx;
		}
		else { // num_member[rx] == num_member[ry]
			if (rx < ry) {
				num_member[rx] = numOfmember(ry) + numOfmember(rx);
				parent[ry] = rx;
			}
			else {
				num_member[ry] = numOfmember(ry) + numOfmember(rx);
				parent[rx] = ry;
			}
		}
	}
	// xとyが同じ集合に属するか否か
	bool same(int x, int y) {
		return root(x) == root(y); // rootが同じなら同じ集合に含まれる
	}
};

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

	int N, M; cin >> N >> M;
	UF monkey(N);

	for (int i = 0; i < M; i++) {
		int a, b; cin >> a >> b;
		monkey.unite(a, b);
	}

	for (int i = 1; i <= N; i++) {
		cout << monkey.root(i) << endl;
	}


	return 0;
}
0