用并查集判断图是否连通,以及是否存在环~
#include<cstdio> #include<algorithm> #include<cstring> #include<vector> #include<unordered_map> using namespace std; const int maxn=1e6+14; const int inf=1e9; int father[maxn],isRoot[maxn],flag,visit[maxn]; void init () { for (int i=0;i<maxn;i++) father[i]=i; flag=0; fill (isRoot,isRoot+maxn,0); fill (visit,visit+maxn,0); } int findfather (int x) { int a=x; while (x!=father[x]) x=father[x]; while (a!=father[a]) { int z=a; a=father[a]; father[z]=x; } return x; } void Union (int a,int b) { int faA=findfather(a); int faB=findfather(b); if (faA!=faB) father[faA]=faB; } int main () { while (1) { int flag=0,x,y; init (); while (1) { scanf ("%d %d",&x,&y); if (x==0&&y==0) break; if (x==-1&&y==-1) return 0; if (findfather(x)==findfather(y)) flag++; visit[x]=1;visit[y]=1; Union (x,y); } for (int i=0;i<maxn;i++) if (visit[i]) isRoot[findfather(i)]++; int ans=0; for (int i=0;i<maxn;i++) if (isRoot[i]&&visit[i]) ans++; if (ans>1) flag++; //printf ("%d ",ans); if (flag==0) printf ("Yes "); else printf ("No "); } return 0; }