标签:
考察并查集,判断是否成环(是否有同样的父节点),判断连通(是否只有一个根节点)
#include<iostream> #define maxn 100000+5 using namespace std; int a,b; int flag; int father[maxn]; int sign[maxn]; void ready() { for(int i=1;i<maxn;i++) father[i]=i,sign[i]=0; } int dfs(int x) { if(father[x]!=x) { father[x]=father[father[x]]; } return father[x]; } void build(int x,int y) { if(x==y) flag=0; else { if(dfs(x)==dfs(y)) flag=0; else { father[dfs(x)]=dfs(y); } } } int main() { while(cin>>a>>b) { ready(); flag=1; if(a==-1&&b==-1){break;} if(!a&&!b) {cout<<"Yes"<<endl;continue;} build(a,b);sign[a]=sign[b]=1; while(cin>>a>>b&&a&&b) { build(a,b); sign[a]=sign[b]=1; } int k=0; for(int i=1;i<maxn;i++) { if(sign[i]&&dfs(i)==i) k++; } if(k==1&&flag) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
标签:
原文地址:http://blog.csdn.net/zafkiel_nightmare/article/details/45510567