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:
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
题目描述:潜在的朋友圈
输入:第一行n,表示人数;接着n行,每行是第i个人选择的课程数及课程id号。
输出:第一行输出多少个圈,接着输出按照圈里人数的大小递减输出。
解题思路:并查集,求出有多少个朋友圈,按照朋友圈的人数从大到小输出每个圈的人数就行了。
#include<bits/stdc++.h>
using namespace std;
int n, m;
const int maxn = 2000;
vector<int> v[maxn];
int f[maxn], g[maxn];
set<int> s;
int find(int x){
while(f[x]!=x){
x = f[x];
}
return x;
}
void Union(int x, int y){
x = find(x);
y = find(y);
f[x] = y;
}
bool cmp(int a, int b){
return a > b;
}
int main()
{
int k;
scanf("%d", &n);
for(int i=1; i<=n; i++) f[i] = i;
for(int i=1; i<=n; i++){
scanf("%d:", &m);
for(int j=0; j<m; j++){
scanf("%d", &k);
v[k].push_back(i);
s.insert(k);
}
}
set<int>::iterator it;
for(it=s.begin(); it!=s.end(); it++){//课程id
sort(v[*it].begin(),v[*it].end());
int x, y;
for(int i=0; i<v[*it].size(); i++){
if(i==0) x = find(v[*it][i]);
else{
y = find(v[*it][i]);
Union(x,y);
}
}
}
map<int,int> p;
for(int i=1; i<=n; i++) p[find(i)]++;
map<int,int>::iterator it1;
int cnt=0;
for(it1=p.begin(); it1!=p.end(); it1++){
g[cnt++] = it1->second;
}
sort(g,g+cnt,cmp);
printf("%d\n", cnt);
for(int i=0; i<cnt; i++){
if(i) printf(" ");
printf("%d", g[i]);
}
return 0;
}