判断是不是连通且无环的无向图:
1.只能有一个根结点
2.同一条边上的点父亲不能相同
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 100010;
bool vis[MAX];
int father[MAX];
void init(){
for(int i=0; i<MAX; i++){
father[i] = i;
vis[i] = false;
}
}
int find(int x){
if(x != father[x])
father[x] = find(father[x]);
return father[x];
}
int main(){
int a, b, xx, yy;
while(scanf("%d%d",&a,&b) == 2){
if(a == -1 && b == -1) break;
if(a == 0 && b == 0){
puts("Yes");
continue;
}
init();
xx = find(a), yy = find(b);
father[yy] = xx;
vis[a] = vis[b] = true;
int flag = 1;
while(scanf("%d%d",&a, &b) == 2){
if(a == 0 && b == 0) break;
xx = find(a), yy = find(b);
if(xx == yy)
flag = 0;
else
father[yy] = xx;
vis[a] = vis[b] = true;
}
if(!flag){
puts("No");
}
else{
for(int i=0; i<MAX; i++)
if(vis[i] && father[i] == i)
flag++;
if(flag == 2) puts("Yes");
else puts("No");
}
}
return 0;
}