After judging the Oraton road, the DFS simple pruning solves the Euler path with the smallest dictionary order.
Time:16ms memory:228k#include<iostream> #include <cstring> #include <cstdio> #include < algorithm>using namespace std; #define MAX 1005#define maxs 24//Name # define MAXN 26//Letter struct edge{char name[maxs]; int A, B; friend bool operator < (Edge &e1, Edge &e2) {return strcmp (E1.name, E2.name) < 0;}} E[max];int N;int IN[MAXN], OUT[MAXN]; In degrees and out of int order[max]; Sequential path bool V[max];bool dfs (int x, int rk) {if (RK = = N) return true; for (int i = 0; i < n; i++) {if (!v[i] && x = = e[i].a) {V[i] = true; ORDER[RK] = i; if (Dfs (e[i].b, rk+1)) return true; V[i] = false; }} return false;} int main () {//freopen ("In.txt", "R", stdin); int T; scanf ("%d", &t); while (t--) {memset (e,0,sizeof (e)); memset (In,0,sizeof (in)); Memset (out,0,sizeof (out)); memset (order,-1,sizeof (order)); memset (v,false,sizeof (v)); scanf ("%d", &N); composition int st = 26; ST: Start for (int i = 0; i < n; i++) {scanf ("%s", e[i].name); E[I].A = e[i].name[0]-' a '; e[i].b = E[i].name[strlen (e[i].name)-1]-' a '; out[e[i].a]++; in[e[i].b]++; if (E[i].a < st) St = E[I].A; } sort (e,e+n); Euler road judgment int odd = 0; Number of singularity nodes bool flag = TRUE; for (int i = 0; i < MAXN; i++) {if (In[i]! = Out[i]) {odd++; if (Out[i]-in[i] = = 1) st = i; else if (Out[i]-in[i]! =-1) {flag = false; Break }}} if (flag && odd ==2 | | odd = 0) && dfs (st,0))//Meet Oraton Road (exclude non-connected) + Full path (non-connected) {for (int i = 0; i < n-1; i++) printf ("%s.", E[order[i]].name); printf ("%s\n", E[ordeR[n-1]].name); } else printf ("***\n"); } return 0;}
ACM/ICPC DFS Solution Euler pathway Path (POJ2337)