[BZOJ1550]避开怪兽

来源:互联网 发布:淘宝两颗心 编辑:程序博客网 时间:2024/04/29 23:41
题目描述
给出一个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+

样例输出
输出样例一:

输出样例二:

0


题解:

预处理出每一个点与怪兽的最近距离len,因为一条路上的点与某一怪兽距离的最小值不会改变。
然后跑spfa, dis记录当前点与怪兽的最大距离。
题目求一条路径中离怪兽的最小距离s, 再在所有的s中取最大, 
只需跑spfa的时候一直取当前最大, 则一定可以保证这条路径中的最小值在所有路径的最小值中是最大的


#include<cstring>#include<cstdio>#include<queue>using namespace std;const int N=505;int n, m, to[4][2]={ {0, 1}, {0,-1}, {-1,0}, {1,0} };int len[N][N], Vx, Vy, Jx, Jy;struct node { int x, y; node(){} node( int a, int b ) { x=a; y=b; } };queue< node > q;void BFS() {    while( !q.empty() ) {        node s=q.front(); q.pop();        for( int i=0; i<4; i++ ) {int x=s.x+to[i][0], y=s.y+to[i][1];if( x>=1 &&x<=n && y>=1 && y<=m )if( len[x][y]>len[s.x][s.y]+1 )len[x][y]=len[s.x][s.y]+1, q.push( node( x, y ) );}    }}int dis[N][N]; bool used[N][N];int Spfa() {dis[Vx][Vy]=len[Vx][Vy]; q.push( node( Vx, Vy ) );while( !q.empty() ) {node s=q.front(); used[s.x][s.y]=0; q.pop();for( int i=0; i<4; i++ ) {int x=s.x+to[i][0], y=s.y+to[i][1];if( x>=1 &&x<=n && y>=1 && y<=m )if( dis[x][y]<min( dis[s.x][s.y], len[x][y] ) ) {dis[x][y]=min( dis[s.x][s.y], len[x][y] );if( !used[x][y] ) used[x][y]=1, q.push( node( x, y ) );}}}return dis[Jx][Jy];}char s[N];int main() {    scanf( "%d%d", &n ,&m );memset( len, 0x3f, sizeof len );    for( int i=1; i<=n; i++ ) {        scanf( "%s", s+1 );        for( int j=1; j<=m; j++ )            if( s[j]=='+' ) q.push( node( i, j ) ), len[i][j]=0;            else if( s[j]=='V' ) Vx=i, Vy=j;            else if( s[j]=='J' ) Jx=i, Jy=j;    }    BFS();printf( "%d\n", Spfa() );    return 0; }


原创粉丝点击