Find a way

来源:互联网 发布:金融随机分析 知乎 编辑:程序博客网 时间:2024/05/17 09:15
F - Find a way
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki. 
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest. 
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes. 
 

Input

The input contains multiple test cases. 
Each test case include, first two integers n, m. (2<=n,m<=200). 
Next n lines, each line included m character. 
‘Y’ express yifenfei initial position. 
‘M’    express Merceki initial position. 
‘#’ forbid road; 
‘.’ Road. 
‘@’ KCF 
 

Output

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
 

Sample Input

4 4Y.#@.....#..@..M4 4Y.#@.....#..@#.M5 5Y..@..#....#...@..M.#...#
 

Sample Output

668866
 
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<math.h>#include<queue>#include<stack>#include<iostream>#include<algorithm>using namespace std;const int MAXN = 213;char a[MAXN][MAXN];bool vis[MAXN][MAXN];int map[2][MAXN][MAXN];int m,n;int dir[4][2] = {0,1,1,0,0,-1,-1,0};struct node{int x,y,step;};bool ok(int x,int y){if(x<0||x>=n||y<0||y>=m){return false;}else{return true;}}void bfs(int idx,int x,int y){memset(vis,false,sizeof(vis));vis[x][y] = true;queue<node>q;node cur,next;cur.x = x;cur.y = y;cur.step = 0;q.push(cur);while(!q.empty() ){cur = q.front() ;q.pop() ;if(a[cur.x][cur.y] == '@'){map[idx][cur.x][cur.y] = cur.step ;}for(int i=0; i<4; i++){next.x = cur.x + dir[i][0];next.y = cur.y + dir[i][1];if(!vis[next.x][next.y] && a[next.x][next.y] != '#' && ok(next.x,next.y)){vis[next.x][next.y] = true;next.step = cur.step + 1;q.push(next); }}} }int main(){while(cin>>n>>m){int x1,y1,x2,y2;for(int i=0; i<n; i++){for(int j=0; j<m; j++){cin>>a[i][j];if(a[i][j] == 'Y')x1=i,y1=j;else if(a[i][j] == 'M')x2=i,y2=j;}}memset(map,0x3f3f3f3f,sizeof(map));bfs(0,x1,y1);bfs(1,x2,y2);int ans = 0x3f3f3f3f;for(int i=0; i<n; i++){for(int j=0; j<m; j++){if(a[i][j] == '@'){ans = min(ans,map[0][i][j] + map[1][i][j]);}}}printf("%d\n",ans*11);}return 0;}

0 0
原创粉丝点击