[POJ] 3278 Catch That Cow

Catch That Cow
Time Limit: 2000MS      Memory Limit: 65536K
Total Submissions: 100715       Accepted: 31496
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 point K (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 X - 1 or X + 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
Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
Source

USACO 2007 Open Silver

一维的bfs,坑还是有的。
没必要剪枝,会很复杂,时间本来就很宽裕。
注意的一点是,起始点和终点为同一点,不特判的话,就会出现2(先+1再-1)这种答案。
x*2还写成了x^2(逃)

//Writer:GhostCai && His Yellow Duck

#include<iostream>
#include<queue>
#include<cstdlib>
#include<cmath>
using namespace std;

bool vis[200005];
int sx,aimx;

struct point{
    int x,step;
}node,r;

void bfs(int x){
    queue<point> Q;
    node.x = x;
    node.step = 0;
    Q.push(node);
    vis[x] =1;
    while(!Q.empty() ){
        r=Q.front() ;
        Q.pop();
        for(int i=1;i<=3;i++){
            int nx;
            if(i==1 ) nx=r.x+1;//不能剪啦 
            if(i==2) nx=r.x-1;
            if(i==3) nx=r.x*2;//r.x^2! 
            if(nx>=0&&nx<=100000&&!vis[nx]){

                vis[nx]=1;
                node.x = nx;
                node.step =  r.step + 1;
                Q.push(node); 
            }   
            if(nx==aimx){
                cout<<node.step <<endl;
                exit(0);
            }
        }
    }
}
int main(){
    cin>>sx>>aimx;
    if(sx==aimx) {
        cout<<0<<endl;
        return 0;
    }
    bfs(sx);
    return 0; 
}
posted @ 2017-11-25 00:11  GhostCai  阅读(85)  评论(0编辑  收藏  举报