题目链接:https://ac.nowcoder.com/acm/contest/993/F/
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
Farmer John is leaving his house promptly at 6 AM for his daily milking of Bessie. However, the previous evening saw a heavy rain, and the fields are quite muddy. FJ starts at the point (0, 0) in the coordinate plane and heads toward Bessie who is located at (X, Y) (-500 ≤ X ≤ 500; -500 ≤ Y ≤ 500). He can see all N (1 ≤ N ≤ 10,000) puddles of mud, located at points (Ai, Bi) (-500 ≤ Ai ≤ 500; -500 ≤ Bi ≤ 500) on the field. Each puddle occupies only the point it is on.
Having just bought new boots, Farmer John absolutely does not want to dirty them by stepping in a puddle, but he also wants to get to Bessie as quickly as possible. He's already late because he had to count all the puddles. If Farmer John can only travel parallel to the axes and turn at points with integer coordinates, what is the shortest distance he must travel to reach Bessie and keep his boots clean? There will always be a path without mud that Farmer John can take to reach Bessie.
输入描述
* Line 1: Three space-separate integers: X, Y, and N.
* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi
输出描述
* Line 1: The minimum distance that Farmer John has to travel to reach Bessie without stepping in mud.
输入
1 2 7
0 2
-1 3
3 1
1 1
4 2
-1 1
2 2
输出
11
说明
Bessie is at (1, 2). Farmer John sees 7 mud puddles, located at (0, 2); (-1, 3); (3, 1); (1, 1); (4, 2); (-1, 1) and (2, 2).
The best path for Farmer John is (0, 0); (-1, 0); (-2, 0); (-2, 1); (-2, 2); (-2, 3); (-2, 4); (-1, 4); (0, 4); (0, 3); (1, 3); and (1, 2), finally reaching Bessie.
解题思路
题意:求(0, 0)到(x, y)的最小距离。
思路:直接BFS搜索就行了,注意有负数,对x和y都扩大500。
Accepted Code:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
const int MAXM = 1000;
struct edge {
int x, y, t;
}p;
bool vis[MAXN][MAXN];
int arr[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int BFS(int x, int y) {
queue <edge> Q;
vis[500][500] = true;
Q.push((edge){500, 500, 0});
while (!Q.empty()) {
p = Q.front();
Q.pop();
if (!(p.x - x - 500) && !(p.y - y - 500))
return p.t;
for (int i = 0; i < 4; i++) {
int tx = p.x + arr[i][0];
int ty = p.y + arr[i][1];
if (tx >= 0 && tx <= MAXM && ty >= 0 && ty <= MAXM && !vis[tx][ty]) {
Q.push((edge){tx, ty, p.t + 1});
vis[tx][ty] = true;
}
}
}
return 0;
}
int main() {
int x, y, u, v, n;
scanf("%d%d%d", &x, &y, &n);
for (int i = 0; i < n; i++) {
scanf("%d%d", &u, &v);
vis[u + 500][v + 500] = true;
}
printf("%d\n", BFS(x, y));
return 0;
}