C++ 并查集练习题朋友圈

某学校有N个学生,形成M个俱乐部。每个俱乐部里的学生有着一定相似的兴趣爱好,形成一个朋友圈。一个学生可以同时属于若干个不同的俱乐部。根据“我的朋友的朋友也是我的朋友”这个推论可以得出,如果A和B是朋友,且B和C是朋友,则A和C也是朋友。请编写程序计算最大朋友圈中有多少人。

输入格式:

输入的第一行包含两个正整数N(≤30000)和M(≤1000),分别代表学校的学生总数和俱乐部的个数。后面的M行每行按以下格式给出1个俱乐部的信息,其中学生从1~N编号:

第i个俱乐部的人数Mi(空格)学生1(空格)学生2 … 学生Mi

输出格式:

输出给出一个整数,表示在最大朋友圈中有多少人。

输入样例:

7 4
3 1 2 3
2 1 4
3 5 6 7
1 6

输出样例:

4

 注意,并查集本身并不能统计出最大朋友圈中的人数,还需要借助一个数组才能完成统计。这里有一个小技巧就是求最大值和统计可以同时进行。

#include <iostream>
#include <algorithm>
#define MAXN 30005
class UnionFind {
private:
	int* parent;
	int count;
	int* rank;            // rank[i]表示以i为根集合的层数
public:
	UnionFind(int count_) {
		parent = new int[count_];
		rank = new int[count_];
		this->count = count_;
		for (int i = 0; i < count_; i++) {
			parent[i] = i;
			rank[i] = 1;
		}

	}

	~UnionFind() {
		delete[] parent;
		delete[] rank;
	}

	int find(int p) {
		//assert(p >= 0 && p < count);
		while (p != parent[p]) {
			parent[p] = parent[parent[p]];
			p = parent[p];
		}
		return p;
	}

	bool isConnected(int p, int q) {

		return find(p) == find(q);
	}

	void unionElements(int p, int q) {

		int pRoot = find(p);
		int qRoot = find(q);
		if (pRoot == qRoot)
			return;
		if (rank[pRoot] < rank[qRoot])
			parent[pRoot] = qRoot;

		else if (rank[qRoot] < rank[pRoot])
			parent[qRoot] = pRoot;
		else {
			parent[pRoot] = qRoot;
			rank[qRoot]++;
		}
		count--;

	}
	int size() {
		return count;
	}

};


int main()
{
	int N, M, temp,temp1, temp2, K;
	int arr[MAXN] = { 0 };
	std::cin >> N >> M;
	UnionFind U = UnionFind(N);
	for (int i = 0; i < M; i++) {
		std::cin >> K;
		for (int i = 0; i < K; i++) {
			std::cin >> temp;
			if (i == 0)
				temp1 = temp;
			else
				U.unionElements(temp1 - 1, temp - 1);

		}
	}
	int res = 0;
	for (int i = 0; i < N; i++) {
		int root = U.find(i);
		arr[root]++;
		res = std::max(res, arr[root]);
	}
	std::cout << res << std::endl;
		
}

 

点赞