hdu 2612 双bfs最短路

来源:互联网 发布:电脑机箱背板孔位数据 编辑:程序博客网 时间:2024/05/16 15:25

Problem 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
66
88
66

题解:

一开始从每个KFC开始bfs搜索,TLE,原因是多次遍历图。
后来从Y和M开始搜索,用一个三维数组保存路径,求出到每个KFC的最短路径,最后遍历一次图,计算到’@’的和的最小值即可。93ms。

代码:

#include <bits/stdc++.h>using namespace std;struct node{    int x,y;    node(int x,int y):x(x),y(y){}};const int INF = 0x3f3f3f3f;int n,m;int Yx,Yy;int Mx,My;char maze[210][210];int d[2][210][210];int dir[4][2]={{0,-1},{0,1},{-1,0},{1,0}};void bfs(int flag,int x,int y){     for(int i=0;i<n;i++)        for(int j=0;j<m;j++)          d[flag][i][j]=INF;     queue<node> que;     que.push(node(x,y));     d[flag][x][y]=0;     while(que.size())     {        node p = que.front();        que.pop();        for(int i=0;i<4;i++)        {            int nx = p.x+dir[i][0];            int ny = p.y+dir[i][1];            if(nx>=0&&nx<n&&ny>=0&&ny<m&&maze[nx][ny]!='#'&&d[flag][nx][ny]==INF)            {                que.push(node(nx,ny));                d[flag][nx][ny]=d[flag][p.x][p.y]+1;            }        }     }}int main(){    while(scanf("%d%d",&n,&m)!=EOF)    {       for(int i=0;i<n;i++)        for(int j=0;j<m;j++)       {           cin>>maze[i][j];           if(maze[i][j]=='Y')           {               Yx = i;               Yy = j;           }           if(maze[i][j]=='M')           {               Mx = i;               My = j;           }       }       bfs(0,Yx,Yy);       bfs(1,Mx,My);        int ans = INF;        for(int i=0;i<n;i++)          for(int j=0;j<m;j++)          {              if(maze[i][j]=='@')              {                 ans=min(ans,d[0][i][j]+d[1][i][j]);              }          }          cout<<ans*11<<endl;    }    return 0;}