[USACO Dec07] 泥潭

來源:互聯網
上載者:User

152. [USACO Dec07] 泥潭

★☆   輸入檔案:mud.in   輸出檔案:mud.out   簡單對比
時間限制:1 s   記憶體限制:128 MB

譯 by CmYkRgB123

描述

Farmer John在早晨6點準時去給貝茜擠奶,然而昨天晚上下了大雨,他的牧場變得泥濘不堪了。Farmer John的家在座標平面的 (0,0) 處,貝茜在 (X, Y) (-500 ≤ X ≤ 500; -500 ≤ Y ≤ 500)。他看見了所有的 N  (1 ≤ N ≤ 10,000) 個泥潭,分別在 (Ai, Bi) (-500 ≤ Ai ≤ 500; -500 ≤ Bi ≤ 500) 。每個泥潭只佔一個點的位置。

Farmer John 剛剛買了新的靴子,他絕對不想把靴子踩進泥潭弄髒,而他又想儘快的找到貝茜。他已經快晚了,因為他花了大量的時間來找到所有的泥潭的位置。 Farmer John 只能平行於座標軸移動,每次移動一個單位。請你協助 Farmer John 找到一條路,使得 Farmer John 能夠最快的找到貝茜,而且不會弄髒靴子。我們約定一定存在一條路使 Farmer John 找到貝茜。

輸入

* 第 1 行: 三個整數  X, Y, N

* 第 2..N+1 行: 第 i+1 行 包含兩個整數 Ai , Bi

輸出

* 第 1 行: Farmer John 能夠最快的找到貝茜,而且不會弄髒靴子,要走的最小的距離。

範例輸入

 1 2 7

 0 2

 -1 3

 3 1

 1 1

 4 2

 -1 1

 2 2

範例輸出

 11

把 泥潭標記成不可走,然後BFS.

#include<cstdio>#include<queue>using namespace std;const int maxn = 10000+100;int map[1100][1100];bool vis[1100][1100];int dx[]={1,-1,0,0};int dy[]={0,0,-1,1};bool check(int x,int y){    return x>=0&&y<=1000&&y>=0&&y<=1000;}int s_x,s_y;int ans;void bfs(){    queue<int >q;    q.push(500); q.push(500); q.push(0);    vis[500][500]=true;    while(!q.empty()){        int x=q.front(); q.pop();        int y=q.front(); q.pop();        int step=q.front(); q.pop();        if(x==s_x&&y==s_y){            ans=step;            return ;        }        for(int i=0;i<4;i++){            int nx=x+dx[i];int ny=y+dy[i];            if(check(nx,ny)&&!vis[nx][ny]&&map[nx][ny]==0){                vis[nx][ny]=true;                q.push(nx);  q.push(ny); q.push(step+1);            }        }    }}int main(){    freopen("mud.in","r",stdin);    freopen("mud.out","w",stdout);    int n; int a,b;    scanf("%d%d%d",&s_x,&s_y,&n);    s_x+=500;s_y+=500;    for(int i=0;i<n;i++){       scanf("%d%d",&a,&b);       a+=500; b+=500;       map[a][b]=1;    }    bfs();    printf("%d\n",ans);    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.