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:
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:
每个爱好都标记一个最初出现的人的编号,以人为对象,遇到已经标记过的爱好,就用并查集合并,最后统计。
注意事项:如果总是以最新的人为父亲,并查集会有延迟,需要在最后更新一下每个人的父亲再进行统计。
例:更新前:编号-父亲: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个测试点未过。。。不知道可不可行。