并查集
#include <iostream>
#include <cstdio>
using namespace std;
#define _for(i, a, b) for(int i = a; i <= b; ++i)
const int N = 1010;
int father[N];
int ranks[N];
int findFather(int x){
int a = x;
while(father[x] != -1){
x = father[x];
}
while(father[a] != -1){
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void Union(int a, int b){
int faA = findFather(a), faB = findFather(b);
if(faA == faB) return;
if(ranks[faA] < ranks[faB]){
father[faA] = faB;
}else if(ranks[faB] < ranks[faA]){
father[faB] = faA;
}else{
father[faA] = faB;
++ranks[faB];
}
}
bool check(int n){
int cnt = 0;
_for(i, 1, n){
if(father[i] == -1){
++cnt;
}
}
return cnt == 1;
}
int main(){
int n, m;
while(~scanf("%d %d", &n, &m) && n && m){
_for(i, 1, n){
father[i] = -1;
ranks[i] = 1;
}
while(m--){
int x, y;
scanf("%d %d", &x, &y);
Union(x, y);
}
check(n) ? printf("YES\n") : printf("NO\n");
}
return 0;
}
京公网安备 11010502036488号