洛谷题解P2873[USACO07DEC]泥水坑MudPuddles

 

题目描述

清早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.

* 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
1 2 7
0 2
-1 3
3 1
1 1
4 2
-1 1
2 2
输出 #1
11

 

首先这是一道bfs板子题,不会bfs的请自行离开

注意要考虑负数情况

 

具体详解见代码

 1 #include "iostream"
 2 #include "cstdio"
 3 #include "cmath"
 4 #include "cstring"
 5 #include "algorithm"
 6 #include "queue"
 7 #include "vector"
 8 
 9 using namespace std;
10 
11 inline int read(){
12     int r=0,w=1;
13     char ch=getchar();
14     while(ch>'9'||ch<'0'){ if(ch=='-') w=-1;ch=getchar(); }
15     while(ch>='0'&&ch<='9'){ r=r*10+ch-'0'; ch=getchar(); }
16     return r*w;
17 }//快速读入 
18 
19 inline void print(int x){
20     if(x<0) x=-x,putchar('x');
21     if(x>9) print(x/10);
22     putchar(x%10+'0');
23 }//快速输出
24 
25 struct code_x{//用于下面的queue
26     int x,y,ans; //x,y为坐标;ans...不用说了吧 
27 };
28 
29 bool p[1010][1010];
30 //布尔存图,true=有坑 
31 int a,b,x,y,n;
32 //x,y--牛棚坐标;a,b辅助存图;n--泥坑数量 
33 int dx[5]={0,0,0,1,-1};
34 int dy[5]={0,1,-1,0,0};
35 //为了便于分析,我把dx[],dy[]并列定义
36 //排去第0个,1-4为:上下右左 
37 queue<code_x>q;//bfs常见队列 
38 
39 int main(){
40     x=read();y=read();n=read();
41     x+=500;y+=500;
42     for(int i=1;i<=n;i++){
43         a=read();b=read();
44         p[a+500][b+500]=1;
45     }//考虑有负数情况,把x,y都加500 
46     q.push((code_x){500,500,0});//把起点搞进去 
47     while(!q.empty()){//bfs 
48         code_x now=q.front();
49         q.pop();
50         for(int i=1;i<=4;i++){
51             int cx=now.x+dx[i];
52             int cy=now.y+dy[i];
53             if(cx==x&&cy==y){
54                 print(now.ans+1);
55                 return 0;
56             }//到达了牛棚 
57             if(cx>=0&&cy>=0&&cx<=1000&&cy<=1000&&!p[cx][cy]){
58                 p[cx][cy]=true;//标记走过了 
59                 q.push((code_x){cx,cy,now.ans+1});
60             }//能走 
61         }
62     }
63 }
View Code

猜你喜欢

转载自www.cnblogs.com/codingxu/p/11748522.html
今日推荐