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个集合,每个集合中有若干整数,将含有相同整数的集合合并,求出最终得到的集合数量以及每个集合中整数的个数。
思路
并查集的应用。设person数组为最初每个数字所对应的集合编号,初始化为0,则在输入数字h时,若person[h]不为0,则将当前集合与person[h]对应的集合合并。设cnt数组为每个集合中整数的个数,合并集合时更新。但要注意,在数字输入完毕后,应重新遍历cnt数组,将不为集合根结点的结点i对应的cnt[i]置为0,方便最后的输出。
AC代码
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1010;
int person[maxn] = {0}, father[maxn], cnt[maxn] = {0};
int n, m, h, num = 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 faA = findFather(a);
int faB = findFather(b);
if(faA != faB){
father[faA] = faB;
cnt[faB] += cnt[faA];
}
}
bool cmp(int a, int b){
return a > b;
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++){
father[i] = i;
cnt[i] = 1;
}
for(int i = 1; i <= n; i++){
scanf("%d:", &m);
for(int j = 0; j < m; j++){
scanf("%d", &h);
if(person[h] == 0){
person[h] = i;
}
else{ //该数字已在其他集合出现过
Union(person[h], i);
}
}
}
for(int i = 1; i <= n; i++){
if(findFather(i)!= i) cnt[i] = 0;
else num++;
}
sort(cnt + 1, cnt + n + 1, cmp);
printf("%d\n", num);
for(int i = 1; i <= num; i++){
printf("%d", cnt[i]);
if(cnt[i + 1] != 0) printf(" ");
}
return 0;
}