Catch That Cow

来源:互联网 发布:小狐狸 for mac 编辑:程序博客网 时间:2024/06/18 12:50

题目链接
Problem 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.
Example Input
5 17
Example Output
4
注意点:
1.poj上是一组输入,所以下面的代码对,hdu是多组输入,所以每次进行之前
都要清空队列,我们下面的代码,也是以hdu上为准.
2.遇到加法的时候一定要注意是不是越界了,采用剪枝.

#include<iostream>#include<cstring>#include<queue>using namespace std;bool visited[100005];int step[100005];void bfs(int n, int k){    queue <int> Q;    memset(visited,false,sizeof(visited));    memset(step,0,sizeof(step));    while(!Q.empty())        Q.pop();    Q.push(n);    visited[n] = true;    step[n] = 0;    int front, next;    while(!Q.empty()){        front = Q.front();        Q.pop();        if(front==k)            return;        for(int i = 0;i<3;i++){//对应3种交通方式            if(i==0)                next =front - 1;            else if(i==1)                next =front + 1;            else                next =front * 2;            if(next<0||next>100000)//剪枝                continue;            if(!visited[next]){                Q.push(next);                visited[next] = true;                step[next] = step[front] + 1;            }        }    }    return;}int main(){    int N, K;    while(cin>>N>>K){        if(N>=K)            cout<<N-K<<endl;        else{            bfs(N,K);            cout<<step[K]<<endl;        }    }    return 0;}