POJ 3278 - Catch That Cow - [BFS]

題目連接:http://poj.org/problem?id=3278ios

Descriptiongit

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.ui

* Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.spa

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?code

Inputorm

Line 1: Two space-separated integers:  N and  K

Outputblog

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Inputip

5 17

Sample Outputci

4

 

題意:get

有一條數字線段 $[0,100000]$,已知農場主在位置 $N$,逃亡的奶牛在位置 $K$ 不移動,如今農場主在每一分鐘均可以有三種行進方式:

往右走一步,往左走一步,傳送到爲當前位置的兩倍的地方;

求最短多少分鐘能夠抓到奶牛。

 

題解:

顯然是BFS,農場主每行進一次,至關於BFS往下搜一層,那麼全部BFS搜索到的位置的深度就至關於行進時間(而且就是到達這個位置的最短期),

若是某一層遇到了奶牛,就直接終止BFS便可。

時間複雜度:全部的點只會進隊一次,$O(N)$。

 

AC代碼:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

const int maxn=100000;

int n,k;
int d[maxn+10];
bool vis[maxn+10];

inline bool ok(int x)
{
    if(0<=x && x<=maxn) return 1;
    else return 0;
}
void bfs()
{
    queue<int> q;
    q.push(n);
    d[n]=0;
    vis[n]=1;
    while(!q.empty())
    {
        int now=q.front(); q.pop();
        if(now==k) return;
        int x1=now+1,x2=now-1,x3=2*now;
        if(ok(x1) && !vis[x1]) q.push(x1),d[x1]=d[now]+1,vis[x1]=1;
        if(ok(x2) && !vis[x2]) q.push(x2),d[x2]=d[now]+1,vis[x2]=1;
        if(ok(x3) && !vis[x3]) q.push(x3),d[x3]=d[now]+1,vis[x3]=1;
    }
}

int main()
{
    cin>>n>>k;
    memset(vis,0,sizeof(vis));
    bfs();
    cout<<d[k]<<endl;
}
相關文章
相關標籤/搜索