牛客补题(并查集)

Interstellar Love

题意:n组数据,每组数据包括第一行s,c,s表示顶点数,接下来c对数,每对表示两个顶点之间有一条边相连,求图中顶点数大于1的并查集数量和存在环的并查集的数量
代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<unordered_map>
#include<set>
#include<queue>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#define N 1005
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;

int par[N],num[N],s,c;
bool vis[N];
void init(){
    memset(vis,false,sizeof(vis));
    for(int i=1;i<=s;i++)
        num[i]=1,par[i]=i;
}

int seek(int x){
    return par[x]==x?x:par[x]=seek(par[x]);
}

int main()
{
    int n;
    cin>>n;
    int k=1;
    while(n--){
        cin>>s>>c;
        init();
        int x,y,cou1=0,cou2=0;

        for(int i=0;i<c;i++){
            cin>>x>>y;
            int a=seek(x),b=seek(y);
            if(a!=b){
                par[a]=b;
                num[b]+=num[a];//统计并查集中元素数量
                if(vis[a]||vis[b])
                    vis[b]=true;
            }
            else
                vis[a]=true;//标记存在环的并查集
        }

        for(int i=1;i<=s;i++){
            if(par[i]==i&&num[i]>1){
                cou1++;
                if(vis[i])
                    cou2++;
            }
        }
        printf("Night sky #%d: %d constellations, of which %d need to be fixed.\n\n",k++,cou1,cou2);
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值