AcWing 3587. 连通图
原题链接
简单
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int,int>;
const int N = 1e3+10;
int t,n,m,k,l,r,op,x,y;
int f[N];
int find(int x){
if(f[x]==x)return x;
return find(f[x]);
}
void merge(int x,int y){
x = find(x);
y = find(y);
if(x!=y)f[y] = x;
}
void solve(){
while(cin>>n>>m){
for(int i = 1;i<=n;i++){
f[i] = i;
}
for(int i = 1;i<=m;i++){
cin>>x>>y;
merge(x,y);
}
int cnt = 0;
for(int i = 1;i<=n;i++){
if(find(i)==i)cnt++;
}
if(cnt==1){
cout<<"YES";
}else{
cout<<"NO";
}
cout<<"\n";
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
solve();
return 0;
}