AcWing 4216:图中的环 ← 快读+并查集

15 篇文章 0 订阅
3 篇文章 0 订阅

【题目来源】
https://www.acwing.com/problem/content/4219/

【算法描述】
给定一个 n 个点 m 条边的无向图。
点的编号从 1 到 n。
图中不含重边和自环。
请你对给定图进行判断,如果该图是一个有且仅有一个环的连通图,则输出 YES,否则输出 NO。

【输入格式】
第一行包含两个整数 n,m。
接下来 m 行,每行包含两个整数 a,b,表示点 a 和点 b 之间存在一条无向边。

【输出格式】
如果该图是一个有且仅有一个环的连通图,则输出 YES,否则输出 NO。

【数据范围】
前三个测试点满足 1≤n≤10。
所有测试点满足 1≤n≤100,0≤m≤n(n−1)/2,1≤a,b≤n。

【输入样例1】
6 6
6 3
6 4
5 1
2 5
1 4
5 4

【输出样例1】
YES

【输入样例2】
6 5
5 6
4 6
3 1
5 1
1 2

【输出样例2】
NO

【算法分析】
● 基环树:
https://blog.csdn.net/hnjzsyjyj/article/details/140730215
● 快读:https://blog.csdn.net/hnjzsyjyj/article/details/120131534
● 并查集:https://blog.csdn.net/hnjzsyjyj/article/details/120147618

【算法代码】

#include<bits/stdc++.h>
using namespace std;

const int N=1e6+5;
int pre[N];

int read() { //fast read
    int x=0,f=1;
    char c=getchar();
    while(c<'0' || c>'9') { //!isdigit(c)
        if(c=='-') f=-1;
        c=getchar();
    }
    while(c>='0' && c<='9') { //isdigit(c)
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}

int find(int x) {
    if(x!=pre[x]) pre[x]=find(pre[x]);
    return pre[x];
}

void merge(int x,int y) {
    int a=find(x);
    int b=find(y);
    if(a!=b) pre[a]=b;
}

int main() {
    int n=read(),m=read();
    for(int i=1; i<=n; i++) pre[i]=i;

    int cnt=0;
    for(int i=1; i<=m; i++) {
        int u=read(),v=read();
        if(find(u)==find(v)) cnt++;
        else merge(u,v);
    }

    if(n!=m || cnt!=1) { //The number of edges in the base ring tree must be n
        cout<<"NO"<<endl;
        return 0;
    }

    cout<<"YES"<<endl;
    return 0;
}

/*
in:
6 6
6 3
6 4
5 1
2 5
1 4
5 4

out:
YES
*/




【参考文献】
https://www.acwing.com/solution/content/88282/

https://blog.csdn.net/hnjzsyjyj/article/details/120147618
https://blog.csdn.net/hnjzsyjyj/article/details/120131534




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值