[USACO07DEC]Mud Puddles S

[USACO07DEC]Mud Puddles S

题目描述

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.

清早6:00,Farmer John就离开了他的屋子,开始了他的例行工作:为贝茜挤奶。前一天晚上,整个农场刚经受过一场瓢泼大雨的洗礼,于是不难想见,FJ 现在面对的是一大片泥泞的土地。FJ的屋子在平面坐标\((0, 0)\)的位置,贝茜所在的牛棚则位于坐标\((X,Y)\) \((-500 <= X <= 500; -500 <= Y <= 500)\)处。当然咯, FJ也看到了地上的所有N(1 <= N <= 10,000)个泥塘,第i个泥塘的坐标为 \((A\_i, B\_i)\) \((-500 <= A\_i <= 500;-500 <= B\_i <= 500)\)。每个泥塘都只占据了它所在的那个格子。 Farmer John自然不愿意弄脏他新买的靴子,但他同时想尽快到达贝茜所在的位置。为了数那些讨厌的泥塘,他已经耽搁了一些时间了。如果Farmer John 只能平行于坐标轴移动,并且只在x、y均为整数的坐标处转弯,那么他从屋子门口出发,最少要走多少路才能到贝茜所在的牛棚呢?你可以认为从FJ的屋子到牛棚总是存在至少一条不经过任何泥塘的路径。

输入格式

* Line 1: Three space-separate integers: X, Y, and N.

第1行: 3个用空格隔开的整数:X,Y 和 N

* Lines 2..N+1: Line i+1 contains two space-separated integers: Ai and Bi

第2..N+1行: 第i+1行为2个用空格隔开的整数:A_i 和 B_i

输出格式

* Line 1: The minimum distance that Farmer John has to travel to reach Bessie without stepping in mud.

第1行: 输出1个整数,即FJ在不踏进泥塘的情况下,到达贝茜所在牛棚所需要 走过的最小距离

样例

样例输入

1 2 7
0 2
-1 3
3 1
1 1
4 2
-1 1
2 2

样例输出

11



代码

#include <bits/stdc++.h>
using namespace std;
struct Node{
	int x,y,dis;
};
queue<Node> q;
bool m[1001][1001];
int x,y,n;
const int dx[4]={-1,0,1,0};
const int dy[4]={0,1,0,-1};
bool f(int x,int y)
{
	return x<-500||x>500||y<-500||y>500||m[x+500][y+500];
}
void bfs()
{
	q.push({0,0,0});
	while(!q.empty())
	{
		int nx=q.front().x,ny=q.front().y,val=q.front().dis;
		q.pop();
		if(f(nx,ny)) continue;
		m[nx+500][ny+500]=1;
		if(nx==x&&ny==y)
		{
			cout << val << endl;
			return;
		}
		for(int i=0;i<4;i++)
		{
			q.push({nx+dx[i],ny+dy[i],val+1});
		}
	}
}
int main()
{
	cin >> x >> y >> n;
	while(n--)
	{
		int X,Y;
		cin >> X >> Y;
		m[X+500][Y+500]=1;
	}
	bfs();
	return 0;
}

热门相关:超武穿梭   重生之至尊千金   重生之至尊千金   学霸女神超给力   夫人你马甲又掉了