题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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 4
Y.#@
....
.#..
@..M
4 4
Y.#@
....
.#..
@#.M
5 5
Y..@.
.#...
.#...
@..M.
#...#
Sample Output
66
88
66
Problem solving report:
Description: 两人分别从"Y"和"M"出发,在地图上走,要找一个"@"见面,每走一格花费时间11分钟,求最快的见面时间。
Problem solving: 以两个人分别为起点做BFS,求出两人到每家KFC的各自花费的时间。对全部KFC维护两人到达时间之和的最小值即为答案。
Accepted Code:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 205;
const int inf = 0x3f3f3f3f;
char mp[MAXN][MAXN];
bool vis[MAXN][MAXN];
int r, c, cnt, min_, t[2][MAXN * MAXN];
int dir[][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
map <pair <int, int>, int> KFC;
struct edge {
int x, y, t;
edge(int x_, int y_, int t_) : x(x_), y(y_), t(t_) {}
}Y(0, 0, 0), M(0, 0, 0);
void BFS(edge e, int s) {
int tx, ty;
queue <edge> Q;
Q.push(e);
memset(vis, 0, sizeof(vis));
vis[e.x][e.y] = 1;
while (!Q.empty()) {
edge p = Q.front();
Q.pop();
if (mp[p.x][p.y] == '@')
t[s][KFC[make_pair(p.x, p.y)]] = p.t;
for (int i = 0; i < 4; i++) {
tx = p.x + dir[i][0];
ty = p.y + dir[i][1];
if (tx >= 0 && tx < r && ty >= 0 && ty < c && mp[tx][ty] != '#' && !vis[tx][ty]) {
vis[tx][ty] = 1;
Q.push(edge(tx, ty, p.t + 1));
}
}
}
}
int main() {
while (~scanf("%d%d", &r, &c)) {
KFC.clear();
cnt = 0, min_ = inf;
memset(t, 0x3f, sizeof(t));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf(" %c", &mp[i][j]);
if (mp[i][j] == 'Y')
Y = edge(i, j, 0);
else if (mp[i][j] == 'M')
M = edge(i, j, 0);
else if (mp[i][j] == '@')
KFC[make_pair(i, j)] = cnt++;
}
}
BFS(Y, 0), BFS(M, 1);
for (int i = 0; i < cnt; i++)
min_ = min(min_, t[0][i] + t[1][i]);
printf("%d\n", min_ * 11);
}
return 0;
}