HDU 2612 - Find a way - [BFS]

題目連接:http://acm.hdu.edu.cn/showproblem.php?pid=2612php

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.
c++

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
express

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.
ide

Sample Input
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
spa

Sample Output
66
88
66code

 

題意:blog

兩人分別從 "Y" 和 "M" 出發,在地圖上走,要找一個 "@" 碰頭,每走一格花費時間 $11$ 分鐘,求最短的碰頭時間。ip

 

題解:ci

以兩我的分別爲起點作BFS,求出兩人到每家KFC的各自花費的時間。get

對所有KFC維護兩人到達時間之和的最小值即爲答案。

 

AC代碼:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int MAX=205;
const int dx[4]={0,1,0,-1};
const int dy[4]={1,0,-1,0};
int n,m;
char mp[MAX][MAX];
pii Y,M;
int KFCcnt;
map<pii,int> KFC;
int Time[2][MAX*MAX];

queue<pii> Q;
int d[MAX][MAX];
void bfs(pii st,int t)
{
    memset(Time[t],0x3f,sizeof(Time[t]));
    memset(d,-1,sizeof(d));
    Q.push(st); d[st.first][st.second]=0;
    while(!Q.empty())
    {
        pii now=Q.front(); Q.pop();
        if(mp[now.first][now.second]=='@')
            Time[t][KFC[now]]=d[now.first][now.second];
        for(int k=0;k<4;k++)
        {
            pii nxt=now; nxt.first+=dx[k], nxt.second+=dy[k];
            if(mp[nxt.first][nxt.second]=='#') continue;
            if(~d[nxt.first][nxt.second]) continue;
            Q.push(nxt);
            d[nxt.first][nxt.second]=d[now.first][now.second]+11;
        }
    }
}
int main()
{
    for(int i=0;i<MAX;i++) mp[i][0]=mp[0][i]='#';
    while(cin>>n>>m)
    {
        KFCcnt=0; KFC.clear();
        for(int i=1;i<=n;i++)
        {
            scanf("%s",mp[i]+1), mp[i][m+1]='#';
            for(int j=1;j<=m;j++)
            {
                if(mp[i][j]=='@') KFC[make_pair(i,j)]=++KFCcnt;
                if(mp[i][j]=='Y') Y=make_pair(i,j);
                if(mp[i][j]=='M') M=make_pair(i,j);
            }
        }
        for(int j=0;j<=m+1;j++) mp[n+1][j]='#';

        bfs(Y,0);
        bfs(M,1);
        int res=0x3f3f3f3f;
        for(int i=1;i<=KFCcnt;i++) res=min(res,Time[0][i]+Time[1][i]);
        printf("%d\n",res);
    }
}
相關文章
相關標籤/搜索