Judging whether all strings can be connected together is actually to judging whether the constructed directed graph has Euler's loop or Euclidean;
#include<iostream>#include<cstdio>#include<cmath>#include<cstring>#include<string>#include <algorithm>#define N 100010using namespace std;char c[N][2];int al[123];int in[27],out[27];int f[27],ccount;bool yo[26];int tou(int x){ if(f[x]!=x) { f[x]=tou(f[x]); } return f[x];}void build(int x,int y){ int toux=tou(x),touy=tou(y); if(touy!=toux) { ++ccount; f[toux]=touy; }}int main(){ int t,n; scanf("%d",&t); while(t--) { memset(al,0,sizeof(al)); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(yo,0,sizeof(yo)); memset(f,0,sizeof(f)); scanf("%d%*c",&n); int geshu=0; for(int i=0; i<n; i++) { char cc,ccc; scanf("%c",&c[i][0]); if(!yo[c[i][0]-'a']) { yo[c[i][0]-'a']=1; ++geshu; } while(scanf("%c",&cc)&&cc!='\n') { ccc=cc; } c[i][1]=ccc; if(!yo[c[i][1]-'a']) { yo[c[i][1]-'a']=1; ++geshu; } in[c[i][1]-'a']++; out[c[i][0]-'a']++; } for(int i=0; i<26; i++) f[i]=i; ccount=0; for(int i=0; i<n; i++) build(c[i][0]-'a',c[i][1]-'a'); int count=0,flag=1; if(ccount+1!=geshu) flag=0; if(flag) for(int i=0; i<26; i++) { if(in[i]!=out[i]) { count++; if(abs(in[i]-out[i])!=1||count>2) { flag=0; break; } } } if(!flag) printf("The door cannot be opened.\n"); else printf("Ordering is possible.\n"); } return 0;}