PAT甲级1107 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

题目大意

如果有两个人有任意一个爱好相同,那他们俩个就处于同一个社交网络(如果A和B属于同一个社交网络,B和C属于同一个社交网络,那A和C也是处于同一个社交网络),然后求一共形成多少个社交网络。
题目给的样例就是2468一个网络、357一个网络、1自己一个网络

思路

不太会写,看了算法笔记才知道原来是并查集的使用。
大致思路就是写一个father数组,用于表示每个人的网络;再写一个hobby数组,hobby[i] = j表示有爱好i的人是j。刚开始hobby都初始化0。假设现在hobby[i] = j,然后遍历k的爱好发现k也有爱好i,而且爱好i此时不为0,说明j和k是同一个网络的。这时就使用并查集中的Union,将j和k合并。依此类推不停的按爱好合并为不同组,最后得出每个组的人数,然后按题目要求操作。

#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
int father[1001];
int hobby[1001];
int isRoot[1001];
void init(int n);
void Union(int a, int b);
int findFather(int a);
bool cmp(int a, int b) { return a > b; }
int main()
{
	int n;
	cin >> n;
	init(n);
	for (int i = 1; i <= n; i++)
	{
		int ki;
		scanf("%d: ", &ki);
		for (int j = 0; j < ki; j++)
		{
			int h;
			cin >> h;
			if (hobby[h] == 0)
				hobby[h] = i;
			Union(i, findFather(hobby[h]));
			//hobby[h]就是表示第一个有这个爱好的人
			//然后让i和这个人合并
		}
	}
	for (int i = 1; i <= n; i++)
		isRoot[findFather(i)]++; //这个根结点的组员人数递增
	int total = 0;
	for (int i = 1; i <= n; i++)
		if (isRoot[i] > 0)
			total++;
	cout << total << endl;
	sort(isRoot + 1, isRoot + n + 1, cmp);
	for (int i = 1; i <= total; i++)
	{
		if (i != 1)
			cout << " ";
		cout << isRoot[i];
	}
	system("pause");
	return 0;
}
void init(int n)
{
	for (int i = 1; i <= n; i++)
		father[i] = i;
}
void Union(int a, int b)
{
	int faA = findFather(a);
	int faB = findFather(b);
	if (faA != faB) //在同一组中的人不会合并
		father[faA] = faB;
}
int findFather(int a)
{
	while (a != father[a])
		a = father[a];
	return a;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值