【天梯选拔&月赛】参与者人数(并查集模版题!remember find_father写法!)

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/88343613

题目:


临沂大学有很多社团,一个学生可能会加入多个社团。为了活跃大学生业余生活,增强体育运动积极性,临沂大学读书社团决定举行大学生跳绳比赛,要求该社团成员必须参加。为了扩大影响,要求只要其他社团有一个人参加,那么该社团中的每一个人都必须参加。求参加比赛至少多少人?

输入格式:

输入第一行包含两个整数n和m,n(0 < n <= 30000)表示学生的数目,m(0 <= m <= 500)表示社团的数目。每个学生都有一个唯一的编号,编号取值为0到n-1,编号为0的社团是读书社团。 接下来有m个社团的名单,每个社团的名单在输入中为一行。每一行先输入一个数k表示社团总人数。接着是社团中k个成员的编号。

输出格式:

输出一个数占一行,表示参加比赛的总人数。

输入样例:

100 4 
2 1 2 
5 10 13 11 12 14 
2 0 1 
2 99 2 
输出样例:

4

解题思路:


并查集,注意要让同一个集合内的所有结点的父亲直接指向集合的根,否则find_father起来会有很多重复的操作,超时!!

更新find_father(int x)的写法:

原写法:

int findfather(int x)
{
    while(x!=father[x])
        x=father[x];
    return x;
}

新的写法:!!!

int find_father(int x)
{
    int fx = father[x];
    return x == fx ? x : father[x] = find_father(fx);
}

Union函数能不调用尽量不调用,否则会段溢出或者超时!

ac代码:


#include <bits/stdc++>
#define maxn 30005
#define inf 0x3fffffff
using namespace std;
typedef long long ll;
int father[maxn];
int find_father(int x)
{
    int fx = father[x];
    return x == fx ? x : father[x] = find_father(fx);
}
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    int n,m,k,t,x,c,ans=0,vis[maxn];
    memset(vis,0,sizeof(vis));
    scanf("%d %d",&n,&m);
    for(int i=0;i<n;i++)
        father[i]=i;
    for(int i=0;i<m;i++)
    {
        scanf("%d %d",&k,&x);
        int fx=find_father(x);
        vis[x]=1;
        if(i==0) t=x;
        for(int j=1;j<k;j++)
        {
            scanf("%d",&c);
            vis[c]=1;
            int fc=find_father(c);
            if(fc!=fx)//main内写,避免调用,超时
                father[fc]=fx;
        }
    }
    int ft=find_father(t);
    for(int i=0;i<n;i++)
        if(vis[i])
        {
            if(ft==find_father(i))
                 ans++;
        }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/88343613