【题目来源】
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