1. 程式人生 > >PAT (Advanced Level) Practice 1107 Social Clusters (30 分)

PAT (Advanced Level) Practice 1107 Social Clusters (30 分)

 

1107 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​​: h​i​​[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:

每個愛好都標記一個最初出現的人的編號,以人為物件,遇到已經標記過的愛好,就用並查集合並,最後統計。

注意事項:如果總是以最新的人為父親,並查集會有延遲,需要在最後更新一下每個人的父親再進行統計。

例:更新前:編號-父親:1-1,2-6,3-5,4-6,5-7,6-8,7-7,8-8,其中2,3,4,都沒有找到最終的父親。

       更新後:編號-父親:1-1,2-8,3-7,4-8,5-7,6-8,7-7,8-8

原始碼1:

#include<iostream>
#include<algorithm>
#include<map>
#include<stdlib.h>
using namespace std;
bool cmp(int a, int b)
{
	return a > b;
}
int cnt[1001] = { 0 }, book[1001];
int getfather(int x)
{
	if (x == book[x])return x;
	else return book[x] = getfather(book[x]);
}
void merge(int x, int y)
{
	int fx, fy;
	fx = getfather(x);
	fy = getfather(y);
	if (fx!=fy)	book[fy] = fx;
	return;
}
int main()
{
	int n, k, htemp, ftemp, i, j,mmax=0;
	map<int, int>mmap;
	scanf("%d", &n);
	for (i = 1; i <=n; i++)	book[i] = i;
	for (i = 1; i <= n; i++)
	{
		scanf("%d:", &k);
		for (j = 0; j < k; j++)
		{
			scanf("%d", &htemp);
			if (mmap[htemp] == 0)mmap[htemp] = i;
			else merge(i, mmap[htemp]);
		}
	}
	for (i = 1; i <= n; i++)getfather(i);
	for (i = 1; i <= n; i++)
	{
		if (book[i] == i)mmax++;
		cnt[book[i]]++;
	}
	sort(cnt, cnt + n+1, cmp);
	printf("%d\n%d", mmax, cnt[0]);
	for (i = 1; i < mmax; i++)printf(" %d", cnt[i]);
	system("pause");
	return 0;
}

題解2:

把愛好作為物件進行合併,還有4個測試點未過。。。不知道可不可行。