Catch That Cow(poj 3278)

给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数

//广搜,a是队列,step记录步数,vis记录哪些数被搜到过 
#include<cstdio>
#include<iostream>
#define M 1000010
using namespace std;
int step[M],a[M],vis[M];
int main()
{
    int n,m,head=0,tail=1;
    scanf("%d%d",&n,&m);
    a[1]=n;
    vis[n]=1;
    while(head<tail)
    {
        ++head;
        int u=a[head];
        if(u==m)
        {
            printf("%d",step[head]);
            return 0;
        }
        if(u-1>=0&&!vis[u-1])
        {
            a[++tail]=u-1;
            step[tail]=step[head]+1;
            vis[u-1]=1;
        }
        if(u+1<1000000&&!vis[u+1])
        {
            a[++tail]=u+1;
            step[tail]=step[head]+1;
            vis[u+1]=1;
        }
        if(u*2<1000000&&!vis[u*2])
        {
            a[++tail]=u*2;
            step[tail]=step[head]+1;
            vis[u*2]=1;
        }
    }
    return 0;
} 
View Code

 

posted @ 2016-06-29 17:56  karles~  阅读(197)  评论(0编辑  收藏  举报