Each letter is treated as a node, and each word is viewed as a forward edge from the first letter to the last letter. The end-to-end of these words is equivalent to looking for a European path (a stroke).
It is required to meet two conditions: 1. After ignoring the direction of the edge, the original is connected. 2. The degree of penetration of one point is 1, the other is 1 less than the degree of penetration, and the other points are equal in degrees.
1#include <cstdio>2#include <cstring>3 using namespacestd;4 int inch[ -], out[ -],n;5 BOOLb[ -],map[ -][ -];6 voidDfsintp)7 {8 inti,j,k;9b[p]=1;Ten for(i=0; i<= -; i++) One if(map[p][i]&&!B[i]) A DFS (i); - } - BOOLOK () the { - inti,j,k,x,y,z; - BOOLb1,b2; -B1=b2=0; + for(i=0; i<= -; i++) - if(inch[i]!= out[i]) + { A if(inch[i]== out[i]+1) at { - if(!B1) -b1=1; - Else - return 0; - } in Else - { to if(inch[i]== out[i]-1) + { - if(!B2) theB2=1; * Else $ return 0;Panax Notoginseng } - Else return 0; the } + } A if(B1!=B2)return 0; theI=0; + while(inch[i]==0&& out[i]==0) i++; - DFS (i); $ for(i=0; i<= -; i++) $ if((inch[i]| | out[i]) &&!b[i])return 0; - return 1; - } the intMain () - {Wuyi inti,j,k,m,p,q,x,y,z,t; the Chars[100010]; -scanf"%d",&t); Wu for(i=1; i<=t;i++) - { AboutMemsetinch,0,sizeof(inch)); $Memset out,0,sizeof( out)); -memset (b,0,sizeof(b)); -memset (Map,0,sizeof(map)); -scanf"%d\n",&n); A for(j=1; j<=n;j++) + { the gets (s); -map[s[0]-'a'][s[strlen (s)-1]-'a']=map[s[strlen (s)-1]-'a'][s[0]-'a']=1; $ inch[S[strlen (s)-1]-'a']++; the out[s[0]-'a']++; the } the if(OK ()) printf ("Ordering is possible.\n"); the Elseprintf"The door cannot be opened.\n"); - } in}
View Code
UVA 10129 play on Words--yhx