PTA-7-25 朋友圈(并查集)

题目:https://pintia.cn/problem-sets/15/problems/840

某学校有N个学生,形成M个俱乐部。每个俱乐部里的学生有着一定相似的兴趣爱好,形成一个朋友圈。一个学生可以同时属于若干个不同的俱乐部。根据“我的朋友的朋友也是我的朋友”这个推论可以得出,如果A和B是朋友,且B和C是朋友,则A和C也是朋友。请编写程序计算最大朋友圈中有多少人。

输入格式:

输入的第一行包含两个正整数N(≤30000)和M(≤1000),分别代表学校的学生总数和俱乐部的个数。后面的M行每行按以下格式给出1个俱乐部的信息,其中学生从1~N编号:

第i个俱乐部的人数Mi(空格)学生1(空格)学生2 … 学生Mi

输出格式:

输出给出一个整数,表示在最大朋友圈中有多少人。

输入样例:

7 4
3 1 2 3
2 1 4
3 5 6 7
1 6

输出样例:

4
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int type;
#define MAX 30001
int tree[MAX];

int FindHead(int x){                     //找到x的父节点
    if(tree[x]<0)
        return x;
    return tree[x]=FindHead(tree[x]);
}

int Union(int h1,int h2){               //两集合并入到最大的集合,并返回最大集合的根结点
        if(tree[h1]<tree[h2]){          //若h1集合大于h2集合
            tree[h1]+=tree[h2];         //h1集合数量等于两者的和
            tree[h2]=h1;                //h2的父节点为h1
            return h1;
        }
        else{
            tree[h2]+=tree[h1];
            tree[h1]=h2;
            return h2;
        }
}

int main(){
        int n,m,s,x,head,h1,h2;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
            tree[i]=-1;

        for(int i=0;i<m;i++){
           scanf("%d%d",&s,&head);
            h1=FindHead(head);
           for(int j=1;j<s;j++){
             scanf("%d",&x);
             h2=FindHead(x);
             if(h1!=h2)
                h1=Union(h1,h2);
           }
        }
    int max=-1;
    for(int i=1;i<=n;i++){
        if(-tree[i]>max&&tree[i]<0)
            max=-tree[i];
    }
    printf("%d\n",max);
}

猜你喜欢

转载自blog.csdn.net/qq_39681830/article/details/81297171