A1107 Social Clusters (30 point(s))

并查集应用

1. 原文

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 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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4 3 1

2. 解析

统计的是人数,将i进行集合,爱好进行hobbies[a]=i,匹配i

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<cstdio>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
map<int,int> hobbies,isroot;
vector<int> v;
int father[1010]={};
void init()
{
for (int i = 0; i < 1010; ++i)
{
father[i]=i;
}
}
int findFather(int x)
{
int a=x;
while(x!=father[x]){
x=father[x];
}
while(a!=father[a]){
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
void together(int a,int b)
{
int fatherA=findFather(a);
int fatherB=findFather(b);
if (fatherA!=fatherB)
{
father[fatherA]=fatherB;
}
}
bool cmp(int x,int y){
return x>y;
}
int main()
{
init();
int n;
scanf("%d",&n);
int k,a;
for (int i = 1; i <= n; ++i)
{
scanf("%d:",&k);
for (int j = 0; j < k; ++j)
{
scanf("%d",&a);
if (hobbies[a]==0)
{
hobbies[a]=i;
}
together(i,findFather(hobbies[a]));
}
}
for (int i = 1; i <= n; ++i)
{
isroot[findFather(i)]++;
}
printf("%lu\n",isroot.size());
for (map<int,int>::iterator i = isroot.begin();
i != isroot.end(); ++i)
{
v.push_back(i->second);
}
sort(v.begin(),v.end(),cmp);
printf("%d",v[0]);
for (int i = 1; i < v.size(); ++i)
{
printf(" %d",v[i]);
}
printf("\n");

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1107/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:07
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!