# PTA 1107 Social Clusters (30 分)

## 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:

Ki : hi[1] hi[2] ... hi[Ki]
where Ki(>0) is the number of hobbies, and hi[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.

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 <algorithm>

using namespace std;

const int N = 1010;
int a[N],used[N],root[N],sum[N];

int find(int x)
{
return x == a[x] ? x : a[x] = find(a[x]);
}

void merge(int x, int y)
{
a[find(y)] = find(x);
}

int main()
{
int n;

for(int i = 0; i < N; i++) a[i] = i;

scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
int k,x,y;
scanf("%d: %d", &k, &x);
x = find(x);
for(int j = 1; j < k; j++)
{
scanf("%d",&y);
merge(x,y);
}
root[i] = find(x);
}
for(int i = 1; i <= n; i++)
sum[find(root[i])]++;
sort(sum+1,sum+N,greater<int>());
int cnt = 0;
for(int i = 1 ; i <= n && sum[i]; i ++)cnt++;
printf("%d\n",cnt);
for(int i = 1 ; i <= n && sum[i]; i++)
printf("%d%c", sum[i], sum[i+1] == 0 ? '\n' : ' ');

return 0;
}

posted @ 2022-03-03 15:54  别问了我什么都不会  阅读(5)  评论(0编辑  收藏  举报