hdu 1116
欧拉回路,利用并查集来实现;
代码:
#include<cstdio> #include<cstring> #include<vector> using namespace std; int a[30],f[30],b[30]; bool vis[30]; int find(int x) { return f[x]==-1?x:f[x]=find(f[x]); } void combine(int x,int y) { int n=find(x); int m=find(y); if(n!=m) f[n]=m; } bool oula() { int st=-1; for(int i=0; i<26; i++) { if(a[i]||b[i]) if(st==-1)st=find(i); else if(st!=find(i)) return false; } vector<int>v; for(int i=0; i<26; i++) if(a[i]!=b[i]) v.push_back(a[i]-b[i]); return v.size()==0||v.size()==2&&v[1]*v[0]==-1; } int main() { int t,n; char s[1009]; scanf("%d",&t); while(t--) { memset(a,0,sizeof a); memset(f,-1,sizeof f); memset(b,0,sizeof b); int ans=0,cnt=0; bool flag=1; scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%s",&s); int l=strlen(s); int x=s[0]-'a',y=s[l-1]-'a'; a[x]++,b[y]++; combine(x,y); } if(oula()) printf("Ordering is possible.\n"); else puts("The door cannot be opened."); } return 0; }