标签:
题意:给出一张无向图,判定是否有环,判定是否为一棵树;
思路:并查集判环,唯一祖先;
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define M 0x3f3f3f3f int fa[500010],mark[500010]; void init() { for(int i=0;i<=500010;i++) fa[i]=i; } int fin(int x) { while(x!=fa[x]) x=fa[x]; return x; } void combine(int a,int b) { int t1=fin(a); int t2=fin(b); if(t1!=t2) { fa[t1]=t2; } } int main() { int n,m,i,j,k,flag,cnt,num,ans,amin,amax; while(scanf("%d%d",&n,&m)!=EOF) { if(n==-1&&m==-1) break; if(n==0&&m==0) { printf("Yes\n");continue; } init(); memset(mark,0,sizeof(mark)); flag=0;amax=0;amin=M; while(1) { if(n==0&&m==0) break; if(amax<n) amax=n; if(amax<m) amax=m; if(amin>n) amin=n; if(amin>m) amin=m; if(fin(n)==fin(m))//判定是否有环 { flag=1; } combine(n,m); mark[n]=1;mark[m]=1; scanf("%d%d",&n,&m); } if(flag) { printf("No\n");continue; } ans=-1;cnt=0; for(i=amin;i<=amax;i++)//判定是否为树 { if(mark[i]&&fin(i)!=ans) { ans=fin(i); cnt++; } } if(cnt==1) printf("Yes\n"); else printf("No\n"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/dashuzhilin/p/4415587.html