PTA1107-Social Clusters
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
思路
编号为1-n的人因为不同的爱好而被分为不同的圈子,我们利用并查集维护同属于一个圈子的人。
这道题看起来和POJ-1703 Find them,Catch them以及POJ-1182食物链极为相似,其实比它们还要简单一些。
我们只需要把活动的编号和人的编号区分开来,就能将人和活动的编号进行合并解决问题,所以我们只需将活动的编号+n,就能避开1-n所有人的编号,接下来就是进行合并查找了。
为了高效查找,我们使用哈希表利用相同集合元素的根元素相同作为key值,统计数目输出即可。
解决代码
#include<bits/stdc++.h>
using namespace std;
const int maxx=2500;
int a[maxx];
int h[maxx];
bool cmp(int x,int y)
{
return x>y;
}
void init(int n)
{
for(int i=1;i<=n;i++)
{
a[i]=i;
h[i]=0;
}
}
int find(int x)
{
return x==a[x]? x:a[x]=find(a[x]);
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y) return ;
if(h[x]<h[y]) a[x]=y;
else
{
a[y]=x;
if(h[x]==h[y]) h[x]++;
}
}
int main()
{
int n;
cin>>n;
init(2001);
for(int i=1;i<=n;i++)
{
string s;
cin>>s;
int x=s[0]-48;
for(int j=0;j<x;j++)
{
int b;
cin>>b;
unite(i,b+n);
}
}
unordered_map<int,int> m;
for(int i=1;i<=n;i++)
{
m[find(i)]++;
}
int sum=m.size();
cout<<sum<<endl;
vector<int> ans;
for(auto it=m.begin();it!=m.end();it++)
{
ans.push_back(it->second);
}
sort(ans.begin(),ans.end(),cmp);
for(int i=0;i<ans.size()-1;i++)
{
cout<<ans[i]<<' ';
}
cout<<ans[ans.size()-1];
return 0;
}