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: 4Sample Output:
3 4 3 1
首先利用一个set<int> S将所有的爱好的可能值保留下来,利用桶的思想,以一个爱好作为一个桶建一个二维的vector a[maxn],将具有相同爱好的人扔到同一个桶里去
然后将同一个桶里的人用并查集合并到一个集合里,最后统计下集合个数,和集合中的元素的数量排序输出就行了
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
const int maxn = 1000 + 10;
struct node {
int fa, cnt; //fa为父节点编号,cnt为当前集合元素
}f[maxn];
int getf(int x) {
return f[x].fa == x ? x : getf(f[x].fa);
}
void Merge(int x, int y) {
int a = getf(x), b = getf(y);
//大编号并入小编号
if (a != b) {
if (a < b) {
f[b].fa = f[a].fa;
f[a].cnt += f[b].cnt; //更新父节点信息
}
else {
f[a].fa = f[b].fa;
f[b].cnt += f[a].cnt;
}
}
}
bool cmp(int x, int y) {
return x > y;
}
int main()
{
int N;
scanf("%d", &N);
vector<int> a[maxn];
set<int> S;
for (int t = 1; t <= N; t++) {
int K, h;
scanf("%d:", &K);
for (int i = 0; i < K; i++) {
scanf("%d", &h);
S.insert(h);
//爱好h中又多了一个人t
a[h].push_back(t);
}
}
for (int i = 1; i <= N; i++) {
f[i].fa = i;
f[i].cnt = 1;
}
//遍历不可重复集合S中的所有元素即是所有可能的爱好
for (set<int>::iterator i = S.begin(); i != S.end(); i++) {
//将具有相同爱好的人合并到一个集合里去
for (int j = 0; j < a[*i].size() - 1; j++) {
Merge(a[*i][j], a[*i][j + 1]);
}
}
int cou = 0, ans[maxn], len = 0;
for (int i = 1; i <= N; i++) {
if (f[i].fa == i) { //f[i].fa == i
cou++;
ans[len++] = f[i].cnt;
}
}
sort(ans, ans + len, cmp);
printf("%d\n", cou);
for (int i = 0; i < len; i++) {
printf(i == 0 ? "%d" : " %d", ans[i]);
}
puts("");
return 0;
}