Build edges by letter, with the first and trailing letters of each word plus edges. First of all to determine whether connectivity, and then determine the degree of each letter and the degree of the difference in the absolute value is greater than 2, and then the degree and the difference in the absolute values of 1 can not exceed two. You can form Euler's path.
The code is as follows:
#include <iostream> #include <string.h> #include <math.h> #include <queue> #include < algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h>using namespace std; #define LL Long long#define pi ACOs ( -1.0) const int Mod=1e9+7;const int Inf=0x3f3f3f3f;const double eqs=1e-9; const int Maxn=100000+10;char s[1100];int in[30], out[30], bin[30], _hash[30], f[30], vis[30];int find1 (int x) {RET Urn Bin[x]==x?x:bin[x]=find1 (bin[x]);} void join (int x, int y) {int f1=find1 (bin[x]); int F2=find1 (bin[y]); if (F1!=F2) {bin[f2]=f1; }}void init () {memset (in,0,sizeof (in)); Memset (out,0,sizeof (out)); memset (_hash,0,sizeof (_hash)); memset (vis,0,sizeof (VIS)); for (int i=0;i<25;i++) {bin[i]=i; }}int Main () {int T, n, I, Len, sum, CNT, x; scanf ("%d", &t); while (t--) {scanf ("%d", &n);Init (); cnt=0; for (i=0;i<n;i++) {scanf ("%s", s); Len=strlen (s); in[s[len-1]-' a ']++; out[s[0]-' a ']++; Join (s[0]-' a ', s[len-1]-' a '); vis[s[0]-' A ']=vis[s[len-1]-' a ']=1; } for (i=0;i<25;i++) {if (!vis[i]) continue; X=find1 (Bin[i]); if (!_hash[x]) {_hash[x]=1; cnt++; }} if (cnt>1) puts ("The door cannot be opened."); else{sum=0; BOOL flag=0; for (i=0;i<25;i++) {if (ABS (in[i]-out[i)) ==1) {sum+ +; } else if (ABS (In[i]-out[i]) >1) {flag=1; }} if (sum>2| | Flag) puts ("The door cannot be opened."); Else puts ("ordering is possible."); }} return 0;}
HDU 1116 && POJ 1386 Play on Words (Euler path)