PTA-1107 Social Clusters(并查集)

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新西兰做的饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值