题目连接: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); } }