poj---3278---Catch That Cow

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<string.h>
#include<algorithm>

using namespace std;
const int maxn=100007;
int n, k, vis[maxn];;
struct node
{
    int x, step;
};

int bfs()
{
    queue<node>Q;
    node p, q;
    p.x=n;
    vis[p.x]=1;
    p.step=0;
    Q.push(p);
    while(!Q.empty())
    {
        q=Q.front();
        Q.pop();
        if(q.x==k)return q.step;

        for(int i=0; i<3; i++)
        {
            if(i==0)
                p.x=q.x+1;
            if(i==1)
                p.x=q.x-1;
            if(i==2)
                p.x=q.x*2;

            if(p.x>=0&&p.x<=100000&&!vis[p.x])
            {
                vis[p.x]=1;
                p.step=q.step+1;
                Q.push(p);
            }
        }
    }
    return -1;
}
int main()
{
    while(~scanf("%d%d", &n, &k))
    {
        memset(vis, 0, sizeof(vis));
        int ans=bfs();
        printf("%d\n", ans);
    }
    return 0;
}

 

posted @ 2017-04-05 16:32  爱记录一切美好的微笑  阅读(102)  评论(0编辑  收藏  举报