[BZOJ1295][SCOI2009]最长距离(spfa)

题目描述

传送门

题解

没想到SCOI还会有良心水题…
首先spfa求出任意两点之间最少经过多少个障碍物dis。然后暴力枚举任意两点,如果dis<=T,那么用它们俩的欧几里得距离更新答案。

代码

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

int n,m,T;
char s[N];
int a[N][N],dis[N][N],dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
bool vis[N][N];
double ans;
struct hp{int x,y;};
queue  q;

void spfa(int sx,int sy)
{
    int num=(sx-1)*m+sy;
    dis[num][num]=a[sx][sy];
    memset(vis,0,sizeof(vis));vis[sx][sy]=true;
    q.push((hp){sx,sy});
    while (!q.empty())
    {
        hp now=q.front();q.pop();
        vis[now.x][now.y]=false;
        for (int i=0;i<4;++i)
        {
            int x=now.x+dx[i],y=now.y+dy[i];
            if (x<1||x>n||y<1||y>m) continue;
            int num1=(now.x-1)*m+now.y;
            int num2=(x-1)*m+y;
            if (dis[num][num2]>dis[num][num1]+a[x][y])
            {
                dis[num][num2]=dis[num][num1]+a[x][y];
                if (!vis[x][y])
                {
                    vis[x][y]=true;
                    q.push((hp){x,y});
                }
            }
        }
    }
}
double calc(double a,double b,double c,double d)
{
    return sqrt((a-c)*(a-c)+(b-d)*(b-d));
}
int main()
{
    scanf("%d%d%d\n",&n,&m,&T);
    for (int i=1;i<=n;++i)
    {
        gets(s);
        for (int j=1;j<=m;++j)
            a[i][j]=s[j-1]-'0';
    }
    memset(dis,127,sizeof(dis));
    for (int i=1;i<=n;++i)
        for (int j=1;j<=m;++j)
            spfa(i,j);
    for (int i=1;i<=n;++i)
        for (int j=1;j<=m;++j)
            for (int k=1;k<=n;++k)
                for (int l=1;l<=m;++l)
                {
                    int num1=(i-1)*m+j,num2=(k-1)*m+l;
                    if (dis[num1][num2]<=T) ans=max(ans,calc((double)i,(double)j,(double)k,(double)l));
                }
    printf("%0.6lf\n",ans);
}

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