【问题描述】
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
【输入格式】
输入包含若干组数据。
每组数据第一行包含两个整数 n 和 m,表示无向图的点和边数。
接下来 m 行,每行包含两个整数 x,y,表示点 x 和点 y 相连。
点的编号从 1 到 n。
图中可能存在重边和自环。
【输出格式】
每组数据输出一行,一个结果,如果所有顶点都是连通的,输出 YES,否则输出 NO。
【数据范围】
输入最多包含 10 组数据。
1≤n≤1000,
1≤m≤5000,
1≤x,y≤n
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1005;
int pre[maxn];
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,m;
while(cin>>n>>m) {
for(int i=1; i<=n; i++) pre[i]=i;
while(m--) {
int p1,p2;
cin>>p1>>p2;
merge(p1,p2);
}
int ans=0;
for(int i=1; i<=n; i++) {
if(find(i)==i) ans++;
}
if(ans==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
/*
in:
4 3
1 2
2 3
3 2
3 2
1 2
2 3
out:
NO
YES
*/
【参考文献】
https://www.acwing.com/problem/content/description/3590/
https://blog.csdn.net/hnjzsyjyj/article/details/120147618