poj3278——bfs

POJ 3278   对数轴进行一维bfs

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 52161   Accepted: 16355

Description

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 pointK (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* 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.

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

Input

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

Output

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

Sample Input

5 17

Sample Output

4

题意:在数轴上求规定走法的最短路
思路:bfs
很基础的一个bfs,一开始由于边界没控制好RE了好多次,最后发现是处理边界的时候由于语句顺序不对导致vis数组越界了,最终还是AC了过去
//poj3278_bfs
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

const int maxn=100020;
int n,k;
bool vis[maxn];
struct node
{
    int pos,step;
};

int bfs()
{
    memset(vis,0,sizeof(vis));
    queue<node> q;
    q.push({n,0});
    vis[n]=1;
    while(!q.empty()){
        node now=q.front();
        q.pop();
        if(now.pos==k) return now.step;
        int next;
        //move to now.pos-1
        next=now.pos-1;
        if(next>=0&&next<maxn&&!vis[next]){ //控制边界时注意要将vis放在next<maxn之后,避免数组越界
            q.push({next,now.step+1});
            vis[next]=1;
        }
        //move to now.pos+1
        next=now.pos+1;
        if(next<maxn&&!vis[next]){
            q.push({next,now.step+1});
            vis[next]=1;
        }
        //move to now.pos*2
        next=now.pos*2;
        if(next<maxn&&!vis[next]&&next!=0){
            q.push({next,now.step+1});
            vis[next]=1;
        }
    }
    return false;
}

int main()
{
    while(cin>>n>>k){
        cout<<bfs()<<endl;
    }
    return 0;
}
poj3278_bfs

 

posted @ 2015-03-13 10:03  __560  阅读(323)  评论(0编辑  收藏  举报