poj3278

poj3278
手写队列high一high,跑的飞起;

#include<cstdio>
#include<queue>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
#define INF 9999999
const double pi=3.1415926535897932;

typedef long long LL;


//x-1,x+1,2*x

int n,k;

int q[100010];
bool vis[100010];
int st[100010];
int head,tail;

int bfs(int n)
{
    memset(vis,0,sizeof(vis));
    memset(st,0,sizeof(st));
    head=0;tail=1;
    q[head]=n;
    vis[n]=1;
    while(head<tail)
    {
        int x;
        int u=q[head];
        if(u==k)
        {
            return st[u];   
        }
        head++;
        for(int i=0;i<3;i++)
        {
            if(i==0)
                x=u+1;
            if(i==1)
                x=u-1;
            if(i==2)
                x=u*2;
            if(vis[x]||x>100000||x<0)
                continue;
            vis[x]=1;
            q[tail++]=x;
            st[x]=st[u]+1;
        }
    }
    return -1;
}

int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        int ans;
        ans=bfs(n);
        if(ans!=-1)
            cout<<ans<<endl;
    }
    return 0;
}
posted @ 2016-05-25 22:11  see_you_later  阅读(120)  评论(0编辑  收藏  举报