6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1
Yes Yes No
代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int f[100005][2],r[100005]; int find(int x) { if (x!=f[x][1]) f[x][1]=find(f[x][1]); return f[x][1]; } void uni(int x, int y) { x=find(x); y=find(y); if (x==y) return; else { if (r[x]>r[y]) f[y][1]=x; else if (r[x]==r[y]) { r[x]++; f[y][1]=x; } else f[x][1]=y; } } int main () { int a,b,i,j,max=1,t=0; bool mul=false,can=true; memset(f,0,sizeof(f)); memset(r,0,sizeof(r)); for (i=1; i<=100000; i++) f[i][1]=i; while(cin>>a>>b) { if (a==-1 && b==-1) break; if (a==0 && b==0) { int ans=0; if (t==0) { cout<<"Yes"<<endl; t=0; continue; } t=0; if (mul) cout<<"No"<<endl; else { for (i=1; i<=max; i++) if (f[i][0]==1) if (f[i][1]==i) ans++; if (ans==1) cout<<"Yes"<<endl; else cout<<"No"<<endl; } mul=false; memset(f,0,sizeof(f)); memset(r,0,sizeof(r)); for (i=1; i<=100000; i++) f[i][1]=i; max=1; } else { t++; if (a>max) max=a; if (b>max) max=b; f[a][0]=1; f[b][0]=1; if (f[a][1]==f[b][1]) mul=true; if (!mul) uni(a,b); } } return 0; }