zoukankan      html  css  js  c++  java
  • B

    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 - 1 or + 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

    Hint

    The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
     
     
     
     
    AC代码:
     #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    bool used[1000001];//记录经过的点,bool的头文件为string
    int vis[1000001];//记录时间
    int bfs(int s,int e)//s为起点,e为终点
    {
    queue<int> q;//头文件为queue
    int pos=s;
    used[pos]=true;
    vis[pos]=0;//起始时时间为零
    q.push(pos);//队列初始化
    while(!q.empty())
    {
    pos=q.front();//检索队首元素
    q.pop();//出队
    if(pos==e) return vis[pos];//特殊情况当起点就是终点时,返回0
    if(pos+1<=100000&&!used[pos+1])//判断是否可执行
    {
    used[pos+1]=true;//没走过的点就赋为一
    vis[pos+1]=vis[pos]+1;
    q.push(pos+1);//探索完后入队
    }
    if(pos-1>0&&!used[pos-1])
    {
    used[pos-1]=true;
    vis[pos-1]=vis[pos]+1;
    q.push(pos-1);
    }
    if(pos*2<=100000&&!used[pos*2])
    {
    used[pos*2]=true;
    vis[pos*2]=vis[pos]+1;
    q.push(pos*2);
    }
    }
    return 0;
    }
    int main()
    {
    int i,j;
    while(scanf("%d%d",&i,&j)!=EOF)//输入多组数据
    {
    memset(used,false,sizeof(used));//清零
    cout<<bfs(i,j)<<endl;
    }
    return 0;
    }
    分析:就是一个人通过三种不同的走法,要你结合每一种走法求出从起点到终点的最短步数
    思路:用队列和BFS解决,首先将队列初始化,然后当队列非空的时候,考虑特殊情况,接着就进行每一种走法的判断。
    心得:通过做此题加深了我对队列和BFS的认知,另外学会了一个新函数的使用,即memset函数(用来为数据清零,头文件为string);做题时我们要从局部往整体写,先写一个大的框架,再添细节,但我很明显还没有习惯这么做,以后做题要注意这方面的培养,这样会让你做题更加简单。
     
     
     
  • 相关阅读:
    koa学习中的一系列问题-mongodb
    JS基础语法使用
    vue中的this指向问题
    CDN的问题
    vue基本语法及使用
    python自动化读取excel数据,写入excel数据,xlrd、xlutils
    jenkins配置邮件发送功能
    pytest生成的index.html报告发送邮箱后没有样式的解决办法
    pytest命令同时执行多个目录,多个不同目录下的文件
    pytest+jenkins+allure生成报告
  • 原文地址:https://www.cnblogs.com/lbyj/p/5676054.html
Copyright © 2011-2022 走看看