问题 A(1550): 避开怪兽
时间限制: 1 Sec 内存限制: 64 MB
题目描述
给出一个N行M列的地图,地图形成一个有N*M个格子的矩阵。地图中的空地用’.’表示。其中某些格子有怪兽,用’+’表示。某人要从起点格子’V’走到终点格子’J’,他可以向上、下、左、右四个方向行走。因此,起点和终点之间可以有许多条路径。注意:即使是有怪兽的格子,他也可以走上去。 设路径上某个格子的坐标为(R,C),某个怪兽的坐标为(A,B),那么它们之间的曼哈顿距离定义为:|R-A| + |C-B| 显然,地图上可能有许多怪兽,路径上也可能途经许多格子,每个格子到每个怪兽都可以算出之间的曼哈顿距离。 问整条路径中离怪兽的曼哈顿距离最小值最大为多少?
输入
输入格式: 第1行:2个整数N和M(1 ≤ N, M ≤ 500) 接下来N行,每行M个字符,可能是’.’, ‘+’, ‘V’, ‘J’等. 数据保证仅包含1个’V’ 和1个 ‘J’ ,至少有1个’+’
输出
输出格式: 第1行:1个整数,表示最短曼哈顿距离的最大值
样例输入
输入样例1:
4 4
+…
….
….
V..J
输入样例2
4 5
…..
.+++.
.+.+.
V+.J+
样例输出
输出样例一:
3
输出样例二:
0
因为要求一条路使得怪兽最近的距离最远。
于是预处理出每一个点与怪兽的最近距离,因为走得越远与怪兽距离的最小值不会变大,具有单调性,然后跑dijsktra就行了。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
using namespace std;
#define MAXN 250000
#define MAXM
#define INF 0x3f3f3f3f
typedef long long int LL;
struct node
{
int v;
node *next;
}*adj[MAXN+10],Edges[MAXN*4],*New=Edges;
const int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
void addedges(int u,int v)
{
node *p=++New;
p->v=v;
p->next=adj[u];
adj[u]=p;
p=++New;
p->v=u;
p->next=adj[v];
adj[v]=p;
}
int id[510][510];
int weath[MAXN+10];
struct point
{
int x,y;
point(){}
point(int a,int b):x(a),y(b){}
};
int N,M;
int Sx,Sy,Tx,Ty;
queue<point>que1;
void bfs()
{
point now;
while(!que1.empty())
{
now=que1.front();que1.pop();
int nx,ny;
for(int i=0;i<4;++i)
{
nx=now.x+dir[i][0],ny=now.y+dir[i][1];
if(nx<1||ny<1||nx>M||ny>N)continue;
if(weath[id[nx][ny]]>weath[id[now.x][now.y]]+1)
{
weath[id[nx][ny]]=weath[id[now.x][now.y]]+1;
que1.push(point(nx,ny));
}
}
}
}
struct data
{
int pos,w;
data(){}
data(int a,int b):pos(a),w(b){}
bool operator < (const data &a)const
{
return w<a.w;
}
};
int dist[MAXN+10];
bool vis[MAXN+10];
priority_queue<data>que2;
int dijkstra()
{
memset(dist,0x3f,sizeof(dist));
while(!que2.empty())que2.pop();
int S=id[Sx][Sy],T=id[Tx][Ty];
dist[S]=weath[S];
que2.push(data(S,0));
data now;
while(!que2.empty())
{
now=que2.top();que2.pop();
if(vis[now.pos])continue;
else vis[now.pos]=1;
if(now.pos==T)return dist[now.pos];
for(node *p=adj[now.pos];p!=NULL;p=p->next)
if(dist[p->v]>min(dist[now.pos],weath[p->v]))
{
dist[p->v]=min(dist[now.pos],weath[p->v]);
que2.push(data(p->v,dist[p->v]));
}
}
return -1;
}
int main()
{
scanf("%d%d",&M,&N);
int i,j;
memset(weath,0x3f,sizeof(weath));
char s[510];
for(i=1;i<=M;++i)
{
scanf("%s",s+1);
for(j=1;j<=N;++j)
{
id[i][j]=(i-1)*N+j;
if(s[j]=='+')
{
weath[id[i][j]]=0;
que1.push(point(i,j));
}
else if(s[j]=='V')
Sx=i,Sy=j;
else if(s[j]=='J')Tx=i,Ty=j;
}
}
for(i=1;i<=M;++i)
for(j=1;j<=N;++j)
{
if(j!=N)addedges(id[i][j],id[i][j+1]);
if(i!=M)addedges(id[i][j],id[i+1][j]);
}
bfs();
printf("%d\n",dijkstra());
}