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 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 <stdio.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e3+10;
int k;
int n;
int Rank[maxn];
int parent[maxn];
int cnt[maxn];
vector<int> hobbies[maxn];
int findParent(int x)
{
int x_root = x;
while(parent[x_root] != -1)//注意是它的parent不为空
{
x_root = parent[x_root];
}
return x_root;
}
int Union(int x, int y)
{
int x_root = findParent(x);
int y_root = findParent(y);
if(x_root != y_root)
{
if(Rank[x_root] > Rank[y_root]){
parent[y_root] = x_root;
cnt[x_root] += cnt[y_root];
}
else if(Rank[x_root] < Rank[y_root]){
parent[x_root] = y_root;
cnt[y_root] += cnt[x_root];
}
else{
parent[x_root] = y_root;
cnt[y_root] += cnt[x_root];
Rank[y_root]++;
}
return 1;
}
return 0;
}
int main()
{
/*1118 Birds in Forest (25 分)*/
#ifndef ONLINE_JUDGE
freopen("test.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d", &n);
fill(Rank, Rank+maxn, 0);
fill(cnt, cnt+maxn, 1);/*cnt初始化为1,每个合并的时候,加到根节点上*/
fill(parent, parent+maxn, -1);
for(int i = 1; i <= n; i++)
{
scanf("%d: ", &k);
for(int j = 0; j < k; j++)
{
int hobby;
scanf("%d", &hobby);
hobbies[hobby].push_back(i);
}
}
for(int i = 1; i <= 1000; i++)
{
if(hobbies[i].size() > 1)
{
int x = hobbies[i][0];
for(int j = 1; j < hobbies[i].size(); j++)
Union(x, hobbies[i][j]);
}
}
vector<int> ans;
for(int i = 1; i <= n; i++)
{
if(findParent(i) == i)
{/*根节点的parent是它自己*/
ans.push_back(cnt[i]);
}
}
sort(ans.begin(), ans.end());
cout << ans.size() << endl;
for(int i = ans.size()-1; i >= 0; i--)
{
if(i == 0)
cout << ans[i];
else
cout <<ans[i] << " ";
}
}
以上代码可以在parent数组保存内自定义结构体,其中包括其索引和cnt,也就是上述代码中cnt和parent数组合并。