标签:algorithm -- sed lag algo std flag ret name
# include<iostream> # include<string> # include<string.h> # include<queue> # include<stdio.h> # include<math.h> #include <algorithm> using namespace std; #define MAX 2005 int first[MAX],next[MAX],u[MAX],v[MAX],used[MAX],h=1,ct=1,in[MAX],ans[MAX]; int out[MAX],x=0; string s[MAX]; char ch; void AddEdge(int a,int b) { u[h] = a; v[h] = b; out[a]++; in[b]++; next[h] = first[u[h]]; first[u[h]] = h; h++; } int judge(int p) { int count1 = 0; int count2 = 0; int vertex[2]; for(int i=1;i<=p;i++) { if(out[i]-in[i] == 1 ) { if(count1>=1) return -1; vertex[0] = i; count1++; } else if(out[i]-in[i] == -1 ) { if(count2>=1) return -1; vertex[1] = i; count2++; } else if(out[i]-in[i] == 0) { continue; } else //WA原因 { return -1; } } if(count1==1 && count2==1) { return vertex[0]; } else if(count1==0 && count2==0) { for(int i=1;i<=26;i++) { if(in[i]!=0 && out[i]!=0) return i; } } else return -1; } void dfs(int k) //k是出发顶点 { for(int i = 1; i < h; i++) { if(u[i] == k) { //printf("%d %d\n------------\n",u[i],k); if(used[i]!=0) { used[i] = 0; dfs(v[i]); ans[ct++] = i; //printf("%d %d\n------------\n",ct,i); ///求出后答案是倒着的 } } } } int main() { int m,n,i,j; cin>>n; while(n--) { cin>>m; h = 1; x = 0; ct = 1; for(i=0;i<MAX;i++) { first[i] = -1; next[i] = -1; used[i] = 1; in[i] = 0; out[i] = 0; } for(i=1;i<=m;i++) { cin>>s[i]; } sort(s+1,s+m+1); for(i=1;i<=m;i++) { int a,b; a = s[i][0] - ‘a‘ + 1; b = s[i][ s[i].length()-1 ] - ‘a‘ + 1; //printf("%d %d",a,b); AddEdge(a,b); } int k,flag = 1; k = judge(26); /* printf("%d\n------------------\n",k); for(i=1;i<h;i++) { printf("%d %d %d\n",u[i],v[i],used[i]); } printf("\n------------------\n"); */ dfs(k); if(k==-1) { flag = 0; } else { for(i=1;i<h;i++) { if(used[i]!=0) { flag = 0; break; } } } if(flag==1) { for(i=ct-1;i>=1;i--) { if(i!=1) cout<<s[ans[i]]<<"." ; else cout<<s[ans[i]]; } cout<<endl; } else printf("***\n"); } return 0; }
标签:algorithm -- sed lag algo std flag ret name
原文地址:https://www.cnblogs.com/fzuhyj/p/9494969.html