POJ 2949

DFS的SPFA用于判负环

#include<cstring>
#include<cstdio>
#define N 200100
using namespace std;
int n;
int vis[900],k;
int head[N],cnt;
double dis[N],mid;
bool is[N];
int flag;
struct Edge{
    int v,w,next;
}edge[N];
void init(){
    memset(vis,0,sizeof(vis));
    memset(head,-1,sizeof(head));
    k=cnt=0;
}
void addedge(int u,int v,int w){
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int u){
    int i;
    is[u]=1;
    for(i=head[u];i!=-1;i=edge[i].next){
        int v=edge[i].v;
        if(dis[v]+1e-8<dis[u]+(double)edge[i].w-mid){
            dis[v]=dis[u]+(double)edge[i].w-mid;
            if(is[v]){
                flag=1;
                return;
            }
            dfs(v);
            if(flag)return;
        }
    }
    is[u]=0;
}
bool judge(){
    int i;
    for(i=1;i<=n;i++)dis[i]=0;
    memset(is,0,sizeof(is));
    flag=0;
    for(i=1;i<=n;i++){
        dfs(i);
        if(flag)return 1;
    }
    return 0;
}
int main(){
    int i,j,len;
    char str[1100];
    while(scanf("%d",&n)){
        if(!n)break;
        init();
        for(i=1;i<=n;i++){
            scanf("%s",str);
            len=strlen(str);
            if(len==1)continue;
            if(vis[(str[0]-'a')+(str[1]-'a')*26]==0)
                vis[(str[0]-'a')+(str[1]-'a')*26]=++k;
            if(vis[(str[len-2]-'a')+(str[len-1]-'a')*26]==0)
                vis[(str[len-2]-'a')+(str[len-1]-'a')*26]=++k;
            addedge(vis[(str[0]-'a')+(str[1]-'a')*26],vis[(str[len-2]-'a')+(str[len-1]-'a')*26],len);
        }
        double h=1001,l=0;
        bool ok=0;
        while(h-l>1e-8){
            mid=(h+l)/2;
            if(judge()){
                ok=1;
                l=mid;
            }
            else h=mid;
        }
        if(ok==0)printf("No solution.\n");
        else printf("%.2f\n",h+1e-8);
    }
}


你可能感兴趣的:(POJ 2949)