[BZOJ2709][Violet 1]迷宫花园(二分+spfa)

题目描述

传送门

题解

二分答案+spfa判定

代码

#include
#include
#include
#include
#include
#include
using namespace std;
#define N 50005

const double eps=1e-7;
char str[105][105];
double L,ans;int T,n,m,s,t;
int tot,point[N],nxt[N],v[N];double c[N];bool flag[N];
double dis[N];bool vis[N];
queue <int> q;

void clear()
{
    L=ans=0;n=m=s=t=0;
    tot=0;memset(point,0,sizeof(point));
    memset(str,0,sizeof(str));
}
double spfa(int s,int t)
{
    memset(dis,127,sizeof(dis));dis[s]=0;
    memset(vis,0,sizeof(vis));vis[s]=1;
    q.push(s);
    while (!q.empty())
    {
        int now=q.front();q.pop();
        vis[now]=0;
        for (int i=point[now];i;i=nxt[i])
            if (dis[v[i]]>dis[now]+c[i])
            {
                dis[v[i]]=dis[now]+c[i];
                if (!vis[v[i]]) vis[v[i]]=1,q.push(v[i]);
            }
    }
    return dis[t];
}
double check(double mid)
{
    for (int i=1;i<=tot;++i)
        if (flag[i]) c[i]=mid;
    return spfa(s,t);
}
double find()
{
    double l=0,r=10,mid,ans;
    while (r-l>eps)
    {
        mid=(l+r)/2;
        double dist=check(mid);
        if (distelse r=mid;
    }
    return ans;
}
void add(int x,int y,double z,int opt)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z; flag[tot]=opt;
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        clear();
        scanf("%lf",&L);
        scanf("%d%d\n",&n,&m);
        for (int i=1;i<=n;++i)
        {
            gets(str[i]+1);
            for (int j=1;j<=m;++j)
                if (str[i][j]=='S') s=(i-1)*m+j;
                else if (str[i][j]=='E') t=(i-1)*m+j;
        }
        for (int i=1;ifor (int j=1;jif (str[i][j]=='S'||str[i][j]=='E'||str[i][j]==' ')
                {
                    int now=(i-1)*m+j;
                    if (str[i][j+1]=='S'||str[i][j+1]=='E'||str[i][j+1]==' ') add(now,now+1,1,0),add(now+1,now,1,0);
                    if (str[i+1][j]=='S'||str[i+1][j]=='E'||str[i+1][j]==' ') add(now,now+m,0,1),add(now+m,now,0,1);
                }
        ans=find();
        printf("%.5lf\n",ans);
    }
}

你可能感兴趣的:(题解,图论算法,二分)