标签:people int 30 1107 hi hobbies Clusters line find
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.
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 <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;
}
标签:people,int,30,1107,hi,hobbies,Clusters,line,find 来源: https://www.cnblogs.com/sherluoke/p/15960250.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。