重温一下前几天的一个题,放松一下放松一下,今天大家都太强了QAQ
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
题意:给个N,有N个人,接下来按编号1~N的顺序,每行给出一个人的感兴趣的活动,先给个K,表示K个活动,然后引号后面有K个活动编号,表示这个人喜欢这个活动。如果有两个人有任意重叠的喜欢的活动,它们就是一个小圈子的,要求输出有几个小圈子,接下来降序输出每个小圈子有几个人。
思路:并查集大法(千万不要一边读一边合并,不知道为啥一边读一边合并有三个测试点就是过不去,惆怅)↓
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int maxv = 1111;
int fa[maxv],root[maxv];
int findfa(int x)//找爸爸
{
int a=x;
while(x!=fa[x])
{
x=fa[x];
}
while(a!=fa[a])
{
int z=a;
a=fa[a];
fa[z]=x;
}
return x;
}
void uni(int a,int b)//合并两个小朋友
{
int faa=findfa(a);
int fab=findfa(b);
if(faa!=fab)
{
fa[faa]=fab;
}
}
struct node
{
int num;//喜欢该活动的人数
int a[maxv];//喜欢该活动的人的编号
}act[maxv];
int N,K,temp;
int main()
{
scanf("%d",&N);
for(int i=1;i<=N;i++)
{
fa[i]=i;
}
for(int i=1;i<=N;i++)
{
scanf("%d:",&K);
for(int j=1;j<=K;j++)
{
scanf("%d",&temp);
act[temp].a[++act[temp].num]=i;
}
}
for(int i=1;i<maxv;i++)
{
for(int j=2;j<=act[i].num;j++)
{
uni(act[i].a[1],act[i].a[j]);
}
}
for(int i=1;i<=N;i++)
{
root[findfa(i)]++;
}
int co=0;
for(int i=1;i<=N;i++)
{
if(root[i]>0)
co++;
}
printf("%d\n",co);
sort(root+1,root+1+N);
for(int i=N;i>N-co;i--)
{
if(i==N)
printf("%d",root[i]);
else
printf(" %d",root[i]);
}
return 0;
}