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:
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
人是并查集中的元素,合并依据为是否有相同爱好
该题需要反自然顺序输出合并完毕后每个小组的人数,可以利用桶排序先计算各小组人数,在为桶排序的索引排序
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;
#define SUM 1001
struct Person {
//不爱用vector数组
vector<int> hobby;
};
int n, sum_hobby;
int f[SUM];//并查集数组
Person persons[SUM];
int query(int i) {
//查询祖宗结点
if (f[i] == i) {
return f[i];
} else {
f[i] = query(f[i]);
return f[i];
}
}
void merge_hobby(int left, int right) {
//合并两结点
int t1 = query(left);
int t2 = query(right);
if (t1 != t2) {
f[t2] = t1;
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
f[i] = i;
}
for (int i = 1; i <= n; i++) {
int sum_h;
cin >> sum_h;
getchar();
for (int j = 1; j <= sum_h; j++) {
int temp;
cin >> temp;
persons[i].hobby.push_back(temp);
for (int a = 1; a <= i; a++) {
if (find(persons[a].hobby.begin(), persons[a].hobby.end(), temp)
!= persons[a].hobby.end()) {
//如果有相同的爱好,两点合并
merge_hobby(a, i);
}
}
}
}
int book[SUM] = {
0 };
for (int i = 1; i <= n; i++) {
f[i] = query(f[i]);//有的点可能合并中路径压缩不彻底,有几个测试点检测该结果
book[f[i]]++;//先记录各组的人数
if (f[i] == i) {
sum_hobby++;
}
}
cout << sum_hobby << endl;
sort(book, book + SUM, greater<int>{
});//根据人数排序
for (int i = 1; i <= sum_hobby; i++) {
cout << book[i - 1];
if (i != sum_hobby) {
cout << " ";
}
}
return 0;
}