1107 Social Clusters (30 point(s))

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

经验总结:

emmmm 经典的并查集题目,这里要注意一点对于所有的人,都要进行两两判定是否有相同的爱好(除了自己和自己),如果有相同的爱好,就要合并,关于并查集的部分,是最基础的并查集的合并与查找,最后再统计群体的个数以及各个群体内部的人数就行了~

AC代码

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int maxn=1010;
vector<int> Node[maxn],ans;
int n,k,father[maxn],num[maxn]={0};
bool judge(int a,int b)
{
if(Node[a].size()>Node[b].size())
{
int temp=a;
a=b;
b=temp;
}
for(int i=0;i<Node[a].size();++i)
{
vector<int>::iterator res=find(Node[b].begin(),Node[b].end(),Node[a][i]);
if(res!=Node[b].end())
return true;
}
return false;
}
bool cmp(int a,int b)
{
return a>b;
}
int findFather(int x)
{
int a=x;
while(x!=father[x])
x=father[x];
while(a!=father[a])
{
int z=father[a];
father[a]=x;
a=z;
}
return x;
}
void Union(int a,int b)
{
int x=findFather(a);
int y=findFather(b);
if(x!=y)
father[x]=y;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
father[i]=i;
scanf("%d: ",&k);
Node[i].resize(k);
for(int j=0;j<k;++j)
scanf("%d",&Node[i][j]);
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(i!=j&&judge(i,j))
Union(i,j);
for(int i=1;i<=n;++i)
++num[findFather(i)];
for(int i=1;i<=n;++i)
if(num[i]!=0)
ans.push_back(num[i]);
sort(ans.begin(),ans.end(),cmp);
printf("%d\n",ans.size());
for(int i=0;i<ans.size();++i)
printf("%d%c",ans[i],i<ans.size()-1?' ':'\n');
return 0;
}