题目描述
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.
(……)
测试要点
- 输出的最后不要加多余的空格
- 如果只能过前3个测试点,后面的测试点全部显示“答案错误”,则将数组开大点,比题目要求的1000大,我这里开了1010
AC代码
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#define MAX 1010
using namespace std;
int n;
int father[MAX];
int hobby[MAX]={0};
int cnt[MAX]={0};
int m;
void init(int n) {
for(int i=1; i<=n; i++) {
father[i]=i;
}
}
int findFather(int a) {
if(a==father[a])
return a;
while(a!=father[a]) {
a=father[a];
}
return a;
}
void uni(int a, int b){
if(findFather(a)== findFather(b)) {
return;
}
father[findFather(a)]= findFather(b);
}
bool cmp(int a, int b) {
return a>b;
}
int main() {
// fstream fin;
// fin.open("tmp.txt");
// fin>>n;
cin>>n;
init(n);
int maxh=0;
for(int i=1;i<=n;i++) {
int h;
// fin>>m;
// fin.ignore();
cin>>m;
cin.ignore();
for(int j=0;j<m;j++) {
// fin>>h;
cin>>h;
if(hobby[h]==0) {
hobby[h]=i;
} else {
uni(i, hobby[h]);
}
if(h>maxh) {
maxh=h;
}
}
}
for(int i=1; i<=n; i++) {
cnt[findFather(i)]++;
}
sort(cnt+1, cnt+n+1, cmp);
int cntf=0;
for(int i=1;i<=n;i++) {
if(cnt[i]==0) break;
cntf++;
}
cout<<cntf<<endl;
for(int i=1;i<=n;i++) {
if(cnt[i+1]==0) {
cout<<cnt[i];
break;
}
cout<<cnt[i]<<' ';
}
}