PAT 甲级 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: 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
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v[1005];
vector<int> hobby[1005];
int N;
bool visit[1005]={false};
vector<int> ans;
void dfs(int curr,int &num)
{
    visit[curr]=true;
    num++;
    for(int i=0;i<v[curr].size();i++)
    {
        int t=v[curr][i]; //爱好
        for(int j=0;j<hobby[t].size();j++) //拥有该爱好的所有人
        {
            if(!visit[ hobby[t][j] ])
                dfs(hobby[t][j],num);
        }
    }
}
int main(){
    scanf("%d",&N);
    int num,t;
    for(int i=0;i<N;i++)
    {
        scanf("%d:",&num);
        for(int j=0;j<num;j++)
        {
            scanf("%d",&t);
            v[i].push_back(t);
            hobby[t].push_back(i);
        }
    }
    for(int i=0;i<N;i++) 
        if(!visit[i])
        {
            num=0;
            dfs(i,num);
            ans.push_back(num);
        }
    sort(ans.begin(),ans.end());
    printf("%d\n",ans.size());
    int i=ans.size()-1;
    while(i>=0){
        printf("%d%c",ans[i],i==0?'\n':' ');
        i--;
    }
}

发布了174 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41173604/article/details/100224491
今日推荐