1107 Social Clusters (30分)
When register on a social network, you are always asked to specify your hobbies in order to find some potential friends with the same hobbies. A social cluster is a set of people who have some of their hobbies in common. You are supposed to find all the clusters.
Input Specification:
Each input file contains one test case. For each test case, the first line contains a positive integer N (≤1000), the total number of people in a social network. Hence the people are numbered from 1 to N. Then N lines follow, each gives the hobby list of a person in the format:
K
i
: h
i
[1] h
i
[2] … h
i
[K
i
]
where K
i
(>0) is the number of hobbies, and h
i
[j] is the index of the j-th hobby, which is an integer in [1, 1000].
Output Specification:
For each case, print in one line the total number of clusters in the network. Then in the second line, print the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
Sample Output:
3
4 3 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 1002;
int course[maxn]{ 0 };//存储该兴趣爱好的人编号
int pre[maxn]{ 0 };
vector<int>v(maxn);//存储不同社交集群的人数
int find(int x)//并查集模板,查找
{
while (x != pre[x]) x = pre[x];
return x;
}
void merge(int a, int b)//并查集模板,合并
{
int x = find(a);
int y = find(b);
if (x != y) pre[x] = y;
}
bool cmp(int a, int b)//自定义排序
{
return a > b;//加条件回报段错误
}
int main()
{
int n, k, value;//value存储兴趣爱好编号
for (int i = 1; i < maxn; i++) pre[i] = i;//初始化pre数组
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> k;
getchar();
for (int j = 0; j < k; j++)
{
cin >> value;
if (course[value] == 0) course[value] = i;//如果该兴趣爱好还没有划分组,进行另它为i号人的兴趣,course[value]=i;
else merge(i, course[value]);//否则,将i和course[value]的人编号合并。
}
}
int count = 0;//存储集群数
for (int i = 1; i <= n; i++)
{
int fa = find(i);//查找老大
if (v[fa] == 0) count++;//如果没被访问过(人员为0),集群数加一
v[fa]++;//人员数加加
}
cout << count << endl;
sort(v.begin()+1, v.end(), cmp);//降序
int flag = 0;//第一个数不能是空格
for (int i = 1; i <= count; i++)
{
if (v[i] != 0)
{
if (flag++ == 0)cout << v[i];
else cout << " " << v[i];
}
}
}