Word Rings

#include<bits/stdc++.h>
#define eps 1e-4
using namespace std;
const int N=3005,M=1e4+5;
int n,tot,cnt,hsh[N],fro[N];
double dis[N];
bool vis[N];
char s[1005];
struct edge{int to,w,nxt;}e[M<<1];
void add(int x,int y,int z) {
    e[++cnt].to=y,e[cnt].w=z,e[cnt].nxt=fro[x]; fro[x]=cnt;
}

bool SPFA(int u,double ave) {
    vis[u]=1;
    for(int i=fro[u];i;i=e[i].nxt) {
        int v=e[i].to;
        if(dis[v]<dis[u]+e[i].w-ave) {
            dis[v]=dis[u]+e[i].w-ave;
            if(vis[v]) return 1;
            if(SPFA(v,ave)) return 1;
        }
    }
    return vis[u]=0;
}

bool check(double ave) {
    fill(dis,dis+tot+1,0);
    fill(vis,vis+tot+1,0);
    for(int i=1;i<=tot;i++)
     if(SPFA(i,ave)) return 1;
    return 0;
}

int main() {
    while(scanf("%d",&n),n) {
        tot=cnt=0;
        memset(hsh,0,sizeof(hsh));
        memset(fro,0,sizeof(fro));
        for(int i=1;i<=n;i++) {
            scanf("%s",s);
            int len=strlen(s);
            int a=(s[0]-'a')*26+s[1]-'a';
            int b=(s[len-2]-'a')*26+s[len-1]-'a';
            if(!hsh[a]) hsh[a]=++tot;
            if(!hsh[b]) hsh[b]=++tot;
            add(hsh[a],hsh[b],len);
        }
        double l=0,r=1e3,ans=-1;
        while(r-l>eps) {
            double Mid=(l+r)/2;
            if(check(Mid)) l=Mid,ans=Mid;
            else r=Mid;
        }
        if(ans==-1) printf("No solution\n");
        else printf("%.2lf\n",ans);    
    }
}

猜你喜欢

转载自www.cnblogs.com/qq8260573/p/10387074.html
今日推荐