Day9 并查集 判断无向图是否有环

题目链接:点击打开链接

因为没有判断是否有两个点之间没有通道wa

但是后来改了还wa了几次...最后不知怎么的就过了..

代码:

#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
using namespace std;
const int maxn = 100000;
int pre[maxn+5];
bool vis[maxn+5];

int Find(int x){
    int r=x;
    while(pre[r]!=r) r = pre[r];

    int i=x,j;
    while(pre[i]!=r){
        j = pre[i];
        pre[i] = r;
        i = j;
    }

    return r;
}

int main(){

    int x,y,cnt=0;
    for(int i=0; i<=maxn; i++) pre[i] = i;
    memset(vis,false,sizeof(vis));
    bool f = true;

    while(scanf("%d%d",&x,&y)){
        if(x == -1 && y == -1) break;

        if(x==0 && y==0){

            cnt = 0;
            for(int i=0; i<=maxn; i++) {
                if((pre[i] == i) && vis[i]) cnt++;
                pre[i] = i;
            }
            if(cnt>1) f=false;

            if(f) printf("Yes\n");
            else printf("No\n");

            f = true;
            memset(vis,false,sizeof(vis));
            continue;
        }

        vis[x] = vis[y] = true;
        if(x == y) continue;

        int fx = Find(x), fy = Find(y);
        if(fx!=fy){
            pre[fx] = fy;
        } else{
            f = false;
        }

    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值