类似poj 3621。
代码:
//poj 2949 //sep9 #include <iostream> #include <string> #include <map> #include <vector> #include <cmath> using namespace std; const int maxL=1024; const int maxM=100100; char s[maxL]; struct Words { int in,out,len; }word[maxM]; map< string,int > mymap; vector<int> ins[maxM],outs[maxM],g[maxM]; double mid,dis[maxM]; int n,cur,vis[maxM]; bool dfs(int u) { vis[u]=cur; for(int i=g[u].size()-1;i>=0;--i){ int v=g[u][i]; if(dis[u]+mid-word[u].len*1.0<dis[v]){ dis[v]=dis[u]+mid-word[u].len*1.0; if(vis[v]==cur||dfs(v)) return true; } } vis[u]=-1; return false; } bool neg_circle() { memset(vis,-1,(n+1)*sizeof(vis[0])); for(int i=0;i<n;++i) dis[i]=0.0; for(cur=0;cur<n;++cur) if(dfs(cur)) return true; return false; } int main() { while(scanf("%d",&n)==1&&n){ mymap.clear(); for(int i=0;i<1000;++i){ ins[i].clear(); outs[i].clear(); } int t=0; for(int i=0;i<n;++i){ scanf("%s",s); word[i].len=strlen(s); if(word[i].len<2) continue; char tmp[16]; tmp[0]=s[0],tmp[1]=s[1],tmp[2]='\0'; string x=tmp; if(mymap[x]==0) mymap[x]=++t; tmp[0]=s[word[i].len-2],tmp[1]=s[word[i].len-1],tmp[2]='\0'; string y=tmp; if(mymap[y]==0) mymap[y]=++t; word[i].in=mymap[x]; word[i].out=mymap[y]; ins[word[i].in].push_back(i); outs[word[i].out].push_back(i); } for(int i=0;i<n;++i){ g[i].clear(); int u=word[i].out; for(int j=ins[u].size()-1;j>=0;--j) g[i].push_back(ins[u][j]); } double l=0.0,r=1024.0; while(fabs(r-l)>1e-4){ mid=(l+r)/2; if(neg_circle()) l=mid; else r=mid; } if(abs(l)<1.0) printf("No solution.\n"); else printf("%.2lf\n",l+1e-9); } }
时间: 2024-12-20 16:02:02