ACM 之 B - Catch That cow

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
    If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

[hit : (5->17) 5-10-9-18-17 , 一共走了4步 。]

理解

John的牛跑了,他要用最快的方式抓到这头牛,他可以选择后退一步或者前进一步甚至前进当前所在坐标的二倍,找出最快的路径帮他抓到牛。

代码部分

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int con,x,y,f,b[200000];//数组开到这里是极限,再小就会数据溢出。
queue<int>a;
int main()
{
    while(scanf("%d%d",&x,&y)!=EOF)
    {
        while(!a.empty())
        {
            a.pop();
        }
        memset(b,0,sizeof(b));
        a.push(-2);
        con=0;
        f=0;
        if(x==y) 
            {printf("0\n");continue;}
        a.push(x);
        b[x]=1;
        int i=1;
        while(f!=1)
        {
            if(a.front()==-2)
            {
                a.pop();
                con++;
                a.push(-2);
            }
            if((a.front()-1)==y||(a.front()+1)==y||(a.front()*2)==y)
                {f=1;break;}
            if(b[a.front()-1]==0&&a.front()>1&&a.front()<100001)
                {a.push(a.front()-1);b[a.front()-1]=1;}//b数组是存在标记,表示出现过这个数了下次就不要再次运算,可以提高程序效率。
            if(b[a.front()+1]==0&&a.front()>-1&&a.front()<99999)
                {a.push(a.front()+1);b[a.front()+1]=1;}
            if(b[a.front()*2]==0&&a.front()>0&&a.front()<50001)
                {a.push(a.front()*2);b[a.front()*2]=1;}
            a.pop();
            //cout<<i++<<endl;
        }
        printf("%d\n",con);
    }
    return 0;
}

意见反馈 || 任何建议

联系我(新浪)
邮箱:qianlizhihao@gmail.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,487评论 0 23
  • 鬼脚七,名文德,前阿里高管,写了两本书。一本叫《没事别随便思考人生》,一本是今年才出版的《所有经过的路都是必经之路...
    山谷里的百合阅读 4,371评论 0 0
  • 人世喧嚷,语声热浪,鼎沸的故事跌入其中,竟是静默而微茫。想来有些难过,因为爱恨之欲终究无可言说;然而又有窃自的欢喜...
    宛丘子阅读 7,863评论 1 10
  • 孤独有个秘密,但它从来不说 有人在孤独中披荆斩棘 有人在欢乐中日渐消沉 孤独的枷锁是背负每个人的沉重 阳光来了,带...
    白莲花的复仇阅读 1,560评论 0 0
  • 抓教研促质量,一直以来是我校领导大力提倡的教学方针。
    火一样的热情阅读 2,372评论 0 0