问题链接:Problem F
问题简述:
地图上有两个人与多家肯德基,每个人行走一步需要花费11分钟。问两个人到达同一家肯德基的时间和最少是多少?
问题分析:
地图中求最短路径问题,可用BFS。由于问题中有两个人,因此两个人都需要进行一次BFS,又由于有多家肯德基,因此需要对每家肯德基均进行一次求最短路径,最后比较得出最小的结果即可。注意处理好到达的是同一家肯德基的问题,本题并不难
AC通过的C++语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
bool vis[205][205];
char map[205][205];
int kfc[205][205];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int n,m;
struct node{
int x,y,step;
};
void init(){
memset(vis,0,sizeof(vis));
memset(map,'\0',sizeof(map));
memset(kfc,0,sizeof(kfc));
}
bool edge(int x,int y){
if(x>=0&&y>=0&&x<n&&y<m&&map[x][y]!='#'&&vis[x][y]==0){
return 1;
}
else{
return 0;
}
}
int BFS(int x,int y){
queue<node>q;
node p1;
p1.x=x;
p1.y=y;
p1.step=0;
vis[x][y]=1;
q.push(p1);
while(!q.empty()){
node p2;
p2=q.front();
q.pop();
if(map[p2.x][p2.y]=='@'){
kfc[p2.x][p2.y]+=p2.step;
}
for(int i=0;i<4;i++){
int next_x=p2.x+dir[i][0];
int next_y=p2.y+dir[i][1];
if(edge(next_x,next_y)){
p1.x=next_x;
p1.y=next_y;
p1.step=p2.step+11;
vis[p1.x][p1.y]=1;
q.push(p1);
}
}
}
}
int main(){
std::ios::sync_with_stdio(false);
while(cin>>n>>m){
init();
int x1,y1,x2,y2;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[i][j];
if(map[i][j]=='Y'){
x1=i;
y1=j;
}
if(map[i][j]=='M'){
x2=i;
y2=j;
}
}
}
BFS(x1,y1);
memset(vis,0,sizeof(vis));
BFS(x2,y2);
int ans=999999;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(kfc[i][j])
ans=min(ans,kfc[i][j]);
}
}
cout<<ans<<endl;
}
}