团体天梯 L3-003 社交集群 (30 分)

版权声明:有疑问请在评论区回复,邮箱:[email protected] https://blog.csdn.net/qq_40946921/article/details/88087926

L3-003 社交集群 (30 分)

当你在社交网络平台注册时,一般总是被要求填写你的个人兴趣爱好,以便找到具有相同兴趣爱好的潜在的朋友。一个“社交集群”是指部分兴趣爱好相同的人的集合。你需要找出所有的社交集群。

输入格式:

输入在第一行给出一个正整数 N(≤1000),为社交网络平台注册的所有用户的人数。于是这些人从 1 到 N 编号。随后 N 行,每行按以下格式给出一个人的兴趣爱好列表:

K​i​​: h​i​​[1] h​i​​[2] ... h​i​​[K​i​​]

其中K​i​​(>0)是兴趣爱好的个数,h​i​​[j]是第j个兴趣爱好的编号,为区间 [1, 1000] 内的整数。

输出格式:

首先在一行中输出不同的社交集群的个数。随后第二行按非增序输出每个集群中的人数。数字间以一个空格分隔,行末不得有多余空格。

输入样例:

8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4

输出样例:

3
4 3 1
#include <iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
int pre[1001], interest[1001];
int find(int i) {
	return pre[i] == i ? pre[i] : find(pre[i]);
}
void Union(int a,int b) {
	a = find(a), b = find(b);
	if (a != b)
		pre[a] = b;
}
int main() {
	int n, k, m;
	char ch;
	cin >> n;
	for (int i = 0; i <= n; i++) pre[i] = i;
	for (int i = 1; i <= n; i++) {
		cin >> k >> ch;
		for (int j = 0; j < k; j++) {
			cin >> m;
			if (!interest[m])
				interest[m] = i;
			Union(i, find(interest[m]));
		}
	}
	map<int, int> result;
	vector<int> out;
	for (int i = 1; i <= n; i++) 
		result[find(i)]++;
	for (auto &it : result)
		out.push_back(it.second);
	sort(out.begin(), out.end(), greater<int>());
	cout << out.size() << endl;
	for (int i = 0; i < out.size(); i++)
		cout << (i ? " " : "") << out[i];
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40946921/article/details/88087926
今日推荐