给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
输入格式
输入包含若干组数据。
每组数据第一行包含两个整数 n 和 m,表示无向图的点和边数。接下来 m 行,每行包含两个整数 x,y,表示点 x 和点 y相连。
点的编号从 1 到 n。图中可能存在重边和自环。
输出格式
每组数据输出一行,一个结果,如果所有顶点都是连通的,输出 YES,否则输出 NO。
数据范围
输入最多包含 10 组数据。
1≤n≤1000,
1≤m≤5000,
1≤x,y≤n
输入样例:
4 3
1 2
2 3
3 2
3 2
1 2
2 3
输出样例:
NO
YES
#include<iostream>
using namespace std;
int n,m;
const int N=1010;
int f[N];
int find(int x)
{
if(x!=f[x]) f[x]=find(f[x]);
return f[x];
}
int main()
{
while(cin>>n>>m)
{
for(int i=1;i<=n;i++) f[i]=i;
while(m--)
{
int a,b;
cin>>a>>b;
f[find(a)]=find(b);
}
bool res=true;
for(int i=2;i<=n;i++)
{
if(find(i)!=find(1))
{
res=false;
break;
}
}
if(res) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}