hdu 2717 Catch That Cow

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.
 

 

Sample Input
5 17
 

 

Sample Output
4
 
//宽搜上手了~
 
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int n,k;
int visit[100005];

struct node
{
    int x,step;
};

int go(int x)
{
    if(0<=x&&x<=100000&&!visit[x])
    return 1;
    return 0;
}

int bfs()
{
    queue<node> q;
    node st,ed;
    st.x=n;
    st.step=0;
    memset(visit,0,sizeof(visit));
    visit[n]=1;
    q.push(st);
    while(!q.empty())
    {
        st=q.front();
        q.pop();
        if(st.x==k)
        {
            cout<<st.step<<endl;
            return 0;
        }
        ed.x=st.x+1;
        if(go(ed.x))
        {
            ed.step=st.step+1;
            visit[ed.x]=1;
            q.push(ed);
        }
        ed.x=st.x-1;
        if(go(ed.x))
        {
            ed.step=st.step+1;
            visit[ed.x]=1;
            q.push(ed);
        }
        ed.x=st.x*2;
        if(go(ed.x))
        {
            ed.step=st.step+1;
            visit[ed.x]=1;
            q.push(ed);
        }
    }
    return 0;
}

int main()
{
    while(cin>>n>>k)
    {
       bfs();
    }
    return 0;
}

 

posted @ 2016-05-28 20:08  邻家那小孩儿  阅读(117)  评论(0编辑  收藏  举报