码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3278 Catch That Cow(bfs)

时间:2015-04-17 23:36:22      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

题意:给定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;
}

 

POJ 3278 Catch That Cow(bfs)

标签:

原文地址:http://www.cnblogs.com/dashuzhilin/p/4436114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!