HDU2612 find a way

来源:互联网 发布:手机里变钱魔术软件 编辑:程序博客网 时间:2024/06/02 08:03

题意:

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

两次bfs,将每个点到目标点最短路径长度,用数组储存起来。然后找出所有的kfc,通过一个求最小值的过程,找出最小值。
注意:该过程中可能会产生路径长度为零的情况,这里有两种可能。一,该点不能被访问。所以一直都是初始化。为零。二,改点即为起点。因此在找kfc最小之和的情况时。要排除kfc为零的情况。

代码如下:

#include <iostream>#include<queue>#include<cstring>#include<cmath>#include<algorithm>using namespace std;#define N 201char map[N][N];int mapy[N][N];int mapm[N][N];int a,b;int yx,yy,mx,my;int flag;int dx[4]={1,-1,0,0};int dy[4]={0,0,1,-1};void input(){    for(int i=0;i<a;i++)       for(int j=0;j<b;j++)        {             cin>>map[i][j];            if(map[i][j]=='Y')yx=i,yy=j;            else if(map[i][j]=='M')mx=i,my=j;    }//应该是只能这样输入}//已经得到了初始的时候两个人的位置struct node{int x,y;};void bfs(int x,int y,int num[N][N]){    queue<node>q;    node u,v;    u.x=x,u.y=y;    q.push(u);    num[x][y]=0;    //数组代表的两个意思    //1.从起点到达目标位置所走的步数    //2.该点是否被访问过   while(!q.empty())   {    u=q.front();    q.pop();    for(int i=0;i<4;i++){        v.x=u.x+dx[i];        v.y=u.y+dy[i];        if(v.x<a&&v.y<b&&v.x>=0&&v.y>=0&&num[v.x][v.y]==0&&map[v.x][v.y]!='#')        {            num[v.x][v.y]=num[u.x][u.y]+1;            q.push(v);        }    }   }}int main(){    while(cin>>a>>b)    {        memset(mapm,0,sizeof(mapm));        memset(mapy,0,sizeof(mapy));        input();        bfs(yx,yy,mapy);        bfs(mx,my,mapm);        int minsize=1001;        for(int i=0;i<a;i++)            for(int j=0;j<b;j++)//bug出循环条件误判        {            if(map[i][j]=='@'&&mapm[i][j]!=0)                minsize=min(minsize,mapm[i][j]+mapy[i][j]);        }     cout<<minsize*11<<endl;    }    return 0;}