分数 30
全屏浏览题目
切换布局
作者 CHEN, Yue
单位 浙江大学
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
代码长度限制
16 KB
时间限制
1200 ms
内存限制
64 MB
#include<bits/stdc++.h>
using namespace std;
const int N=1009;
int p[N],cnt[N];;
vector<int>v[N];//存储某爱好的所有爱好者
int find(int a){//并查集经典操作,找祖先
if(p[a]!=a)p[a]=find(p[a]);
return p[a];
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++)p[i]=i;
for(int i=1;i<=n;i++){
int k;
scanf("%d: ",&k);
while(k--){//输入k个爱好
int hobby;
cin>>hobby;
v[hobby].push_back(i);//将该爱好者放入他的所有爱好里
}
}
for(int i=1;i<=1000;i++){//遍历所有爱好
for(int j=1;j<v[i].size();j++){//将同一个爱好的爱好者合并同一个并查集里
int a=v[i][0],b=v[i][j];
p[find(a)]=find(b);//并查集的合并操作
}
}
for(int i=1;i<=n;i++)cnt[find(i)]++;//遍历所有人,将该人所在的并查集人数加1
sort(cnt+1,cnt+1+n,greater<int>());//降序排列
int k=1,sum=0;//k作为中间变量用来数集合数,sum记录集合数
while(cnt[k])sum++,k++;//获得并查集数量,即只要有人数k++
cout<<sum<<endl;//输出集合数
cout<<cnt[1];//输出各集合人数
for(int i=2;i<=sum;i++)cout<<' '<<cnt[i];//输出各集合人数
return 0;
}