pat 1107 Social Clusters (30 分)

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

思路:使用并查集,先设每个人的父亲是自己并且设置自己不为群体的根节点,然后遍历每个人的爱好,当一次遇到该爱好就设当前爱好的祖宗为当前人,如果不是第一次遍历到当前爱好则说明有不同的人有相同的爱好这时候就要进行合并。然后对每个人进行遍历,对isroot[他的父亲]++,如果isroot不为0就表示他是一个群体的根,群体数就加一,最后对isroot进行排序输出即可

#include
#include
#define maxn 1001
using namespace std;
int  father[maxn], hobby[maxn] = {0}, isroot[maxn] = {0};
bool cmp(int x, int y){
    return x > y;
}
int findFather(int x){
    while(x != father[x])
        x = father[x];
    return x;
}
void Union(int x, int y){
    int fx = findFather(x);
    int fy = findFather(y);
    if(fx != fy){
        father[fx] = fy; 
    }
}
int main(){
    int n, k, ans = 0;
    cin>>n;
    for(int i = 1; i <= n; i++){
        father[i] = i;
        isroot[i] = 0;
    }
    for(int i = 1; i <= n; i++){
        scanf("%d:", &k);
        for(int j = 0; j < k; j++){
            int t;
            cin>>t;
            //如果当前hobby未被访问则将当前i赋值为当前爱好的祖宗
            if(hobby[t] == 0){
                hobby[t] = i;//这里思维紊乱,没想到可以直接使用hobby[t]表示当前爱好的祖宗,想着用计数来表示相同爱好,如果加1则就把当前人归入并查集,其实只要hobby状态不为0即表示以及有祖宗了。只需合并
            }
            //合并当前i和当前爱好的祖宗
            Union(i, findFather(hobby[t]));
        }
    }
    for(int i = 1; i <= n; i++){
        isroot[findFather(i)]++;
    }
    sort(isroot + 1, isroot + n + 1, cmp);
    for(int i = 1; i <= n; i++){
        if(isroot[i] != 0)
            ans++;
        else 
            break;
    }
    cout<

你可能感兴趣的:(pat,并查集,算法)