1107 Social Clusters (30分)
作者:CHEN, Yue
单位:浙江大学
代码长度限制:16 KB
时间限制:250 ms
内存限制:64 MB
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
题意:
有n个人,如果有喜欢的同一种爱好,那么他俩就是好朋友,而且好朋友的好朋友也是好朋友。求共有几组社交圈子,并降序输出,每个圈子好朋友的个数。
思路:
并查集。要通过爱好去联系人,并查集是将人的序列进行操作。如第1个人的爱好是4这个兴趣,那么4这个兴趣还没有人喜欢过,则记录hobby[4]=1,代表喜欢4这个兴趣的人可以去找1当好朋友,1的好朋友也是你的好朋友。如第4个人的爱好也是4,那么就将第4个人和第一个人组成好朋友,即Union(hobby[4],4)。并查集的时候采用路径压缩,利用哈希表记录朋友的个数。
参考代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1001;
int father[maxn], hobby[maxn] = {0};
int isroot[maxn] = {0};
int findfather(int x) {
if (father[x] == x)return x;
else {
int F = findfather(father[x]);
father[x] = F;
return F;
}
}
void Union(int a, int b) {
int fa = findfather(a);
int fb = findfather(b);
if (fa != fb)
father[fa] = fb;
}
void init() {
for (int i = 0; i < maxn; i++)
father[i] = i;
}
int main() {
init();
int n, k, h, cnt = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d:", &k);
for (int j = 0; j < k; j++) {
scanf("%d", &h);
if (hobby[h] == 0)hobby[h] = i;
else Union(hobby[h], i);
}
}
for (int i = 1; i <= n; i++) {
isroot[findfather(i)]++;
}
vector<int> v;
for (int i = 1; i <= n; i++) {
if (isroot[i] != 0) {
v.push_back(isroot[i]);
cnt++;
}
}
sort(v.begin(), v.end(), greater<int>());
printf("%d\n", cnt);
for (int i = 0; i < v.size(); i++) {
if (i != 0)printf(" ");
printf("%d", v[i]);
}
return 0;
}
如有错误,欢迎指正