1 题目链接
https://vjudge.net/problem/HDU-2612
2 题目大意
Y要去找M玩,他们约定在KFC相见,因为地图上面有很多个KFC,所以要找一个两者到达总时间最少的KFC,两个人每走一步都需要11分钟,求最短时间。
3 样例输入
4 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
其中‘Y’代表Y的初始位置,‘M’代表M的初始位置,’.‘代表可以走的路,’#‘代表不能走的路,’@'代表KFC的位置
注:本处为了博客美观,样例输入的字符用了全角字符,测试数据请从原题获取
4 样例输出
66
88
66
5 代码
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<functional>
#include<vector>
#include<iostream>
#include<time.h>
#include<math.h>
using namespace std;
//-------------------------------------------------------
//#define LL long long
#define LL __int64
template<typename T>T Max(T a, T b){ return a>b ? a : b; }
template<typename T>T Min(T a, T b){ return a<b ? a : b; }
template<typename T>void Swap(T &a, T &b){ T c = a; a = b; b = c; }
template<typename T>T Abs(T a){ return a >= 0 ? a : -a; }
#define clr_all(a,b) memset(a,b,sizeof(a))
#define clr(a,b,n) memset(a,b,sizeof(a[0])*n)
const int MAXN = 200 + 5;
const int MAXM = 200 + 5;
const int mod = 1000000007;
const int INF = 0x7FFFFFFF;
//-------------------------------------------------------
int N, M;
char Map[MAXN][MAXM];
int KFC[MAXN][MAXM];
bool Flag[MAXN][MAXM];
int dir_x[] = { 0, 0, 1, -1 };
int dir_y[] = { 1, -1, 0, 0 };
typedef struct node{
int x, y;
int count;
}Node;
bool Is_OK(int i, int j){
if (i >= 0 && j >= 0 && i < N&&j < M&&Map[i][j] != '#')
return true;
else
return false;
}
queue<Node>q;
void BFS(int n, int m){
clr_all(Flag, 0);
while (!q.empty())
q.pop();
Node tmp;
tmp.x = n, tmp.y = m, tmp.count = 0;
q.push(tmp);
Flag[n][m] = true;
while (!q.empty()){
Node pre = q.front();
q.pop();
for (int i = 0; i < 4; i++){
int x = pre.x + dir_x[i];
int y = pre.y + dir_y[i];
if (Is_OK(x, y) && !Flag[x][y]){
Node now;
now.x = x, now.y = y, now.count = pre.count + 1;
q.push(now);
Flag[x][y] = true;
if (Map[x][y] == '@')
KFC[x][y] += now.count;
}
}
}
}
int main(){
while (~scanf("%d%d", &N, &M)){
clr_all(KFC, 0);
for (int i = 0; i < N; i++)
scanf("%s", Map[i]);
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
if (Map[i][j] == 'Y')
BFS(i, j);
if (Map[i][j] == 'M')
BFS(i, j);
}
}
int Min_time = INF;
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
if (Map[i][j] == '@'&&KFC[i][j] != 0)
Min_time = Min(Min_time, KFC[i][j]);
}
}
printf("%d\n", Min_time * 11);
}
return 0;
}
本文介绍了一种算法,用于解决两人在多个指定地点中找到一个双方到达总时间最短的地点的问题。通过广度优先搜索(BFS),计算每个人到所有KFC的最短路径,然后找出总时间最短的KFC。代码使用C++实现,包含详细的注释说明。
303

被折叠的 条评论
为什么被折叠?



