POJ 3278 Catch That Cow(bfs)

题意:给定n,k两个数,三种操作,加一,减一,乘2,求n到k的最少步数;

思路:广搜求最少步数;

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m;
int q[500010];
int num[500010];
int bfs()
{
    int b=0,e=0;
    q[e++]=n;
    if(n==m) return 0;
    while(b<e)
    {
        int x=q[b++];
        if(x-1==m||x+1==m||x*2==m)
            return num[x]+1;
        else
        {
            if(0<=x-1&&x-1<=100000&&!num[x-1])
            {
                num[x-1]=num[x]+1;q[e++]=x-1;
            }
            if(0<=x+1&&x+1<=100000&&!num[x+1])
            {
                num[x+1]=num[x]+1;q[e++]=x+1;
            }
            if(0<=2*x&&2*x<=100000&&!num[2*x])
            {
                num[2*x]=num[x]+1;q[e++]=2*x;
            }
        }
    }
}
int main()
{
    int i,j,k;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(num,0,sizeof(num));
        printf("%d\n",bfs());
    }
    return 0;
}

 

posted on 2015-04-17 22:37  大树置林  阅读(123)  评论(0编辑  收藏  举报

导航