简单深搜。

 

CODE:

 

#include <iostream>
#include <string.h>
using namespace std;

const int large=200030;

typedef class
{
    public:
        int x;
        int step;
}pos;

int n,k;
bool vist[large];   
pos queue[large];


void BFS(void)
{
    int head,tail;
    queue[head=tail=0].x=n;
    queue[tail++].step=0;

    vist[n]=true;

    while(head<tail)
    {
        pos w=queue[head++];

        if(w.x==k)
        {
            cout<<w.step<<endl;
            break;
        }

        if(w.x-1>=0 && !vist[w.x-1])    
        {
            vist[w.x-1]=true;
            queue[tail].x=w.x-1;
            queue[tail++].step=w.step+1;
        }
        if(w.x<=k && !vist[w.x+1])    
        {
            vist[w.x+1]=true;
            queue[tail].x=w.x+1;
            queue[tail++].step=w.step+1;
        }
        if(w.x<=k && !vist[2*w.x])     
        {
            vist[2*w.x]=true;
            queue[tail].x=2*w.x;
            queue[tail++].step=w.step+1;
        }
    }
    return;
}

int main()
{
    while(cin>>n>>k)
    {
        memset(vist,false,sizeof(vist));
        BFS();
    }
    return 0;
}

 

 

posted on 2012-09-01 19:54  有间博客  阅读(134)  评论(0编辑  收藏  举报