PAT A1107 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.

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:
K​i : hi[1] h​i[2] … h​i[K​i] where K​i(>0) is the number of hobbies, and h​i[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)开数组hobby[],hobby[i]存放第一个输入爱好为i的人员;
(2)通过合并函数Union()将拥有共同爱好的人员不断合并.

代码:

#include 
#include 
using namespace std;
const int maxn = 1010;

int father[maxn];//并查集,每个人员结点的父亲结点 
int isroot[maxn] = {0};//isroot[i]存放以结点i为根结点的结点个数
int hobby[maxn] = {0};//hobby[i]存放第一个输入爱好为i的人员 
bool cmp(int a,int b){
	return a>b;
}
void init(int n){//初始化 
	for(int i=1;i<=n;i++){
		father[i] = i;
		isroot[i] = 0;	
	}
}
int findFather(int x){//找到根结点 
	if(x==father[x]) return x;
	else return findFather(father[x]);
} 
void Union(int a,int b){//合并并查集 
	int faA = findFather(a);
	int faB = findFather(b);
	if(faA!=faB) father[faA] = faB;
}

int main(){
	int n;
	scanf("%d",&n);
	init(n);
	for(int i=1;i<=n;i++){
		int k,h;
		scanf("%d:",&k);
		for(int j=0;j<k;j++){
			scanf("%d",&h);
			if(hobby[h]==0) hobby[h] = i;
			Union(i,findFather(hobby[h]));//不断合并形成聚类 
		}
	}
	for(int i=1;i<=n;i++){
		isroot[findFather(i)]++;
	}
	int number = 0;//聚类个数
	for(int i=1;i<=n;i++){
		if(isroot[i]!=0) number++;
	} 
	printf("%d\n",number);
	sort(isroot+1,isroot+n+1,cmp);
	for(int i=1;i<=number;i++){
		printf("%d",isroot[i]);
		if(i!=number) printf(" ");
	}
	printf("\n");
	return 0;
}

你可能感兴趣的:(PAT甲级,PAT,程序设计,c++,算法,数据结构)