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
将有相同的兴趣(一个或多个相同)的人归类成一个集体,输出集体的个数和各个集体的人数。这里用了两个数组来储存信息,一个储存各个人有哪些兴趣,另一个储存各个兴趣对应的哪些人。然后用bfs,先从某一个兴趣出发,找出对应的人(期间要更新当前集合的人数),然后再根据这些人得到相关的兴趣,然后再从兴趣得到人,从人得到兴趣......这样循环直到当前的兴趣队伍空了。为了防止无限循环,要用两个数组保存哪些人和哪些兴趣被访问过。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
vector<vector<int> >hob(1001);
vector<vector<int> >peo(n);
int Max=0;
for(int i=0;i<n;i++)
{
int k;
cin>>k;
getchar();
for(int j=0;j<k;j++)
{
int h;
cin>>h;
Max=max(Max,h);
peo[i].push_back(h);
hob[h].push_back(i);
}
}
vector<bool>isvis_h(Max+1,false);
vector<bool>isvis_p(n,false);
vector<int>res;
for(int i=1;i<=Max;i++)
{
if(hob[i].size()==0||isvis_h[i]) continue;
int count=0;
queue<int>que;
que.push(i);
while(!que.empty())
{
int tmp=que.front();
que.pop();
isvis_h[tmp]=true;
for(int j=0;j<hob[tmp].size();j++)
{
if(!isvis_p[hob[tmp][j]])
{
count++;
isvis_p[hob[tmp][j]]=true;
for(int k=0;k<peo[hob[tmp][j]].size();k++)
{
if(!isvis_h[peo[hob[tmp][j]][k]])
{
que.push(peo[hob[tmp][j]][k]);
}
}
}
}
}
res.push_back(count);
}
cout<<res.size()<<endl;
sort(res.begin(),res.end(),greater<int>());
cout<<res[0];
for(int i=1;i<res.size();i++)
{
cout<<" "<<res[i];
}
}