博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
B - Catch That Cow
阅读量:4647 次
发布时间:2019-06-09

本文共 2043 字,大约阅读时间需要 6 分钟。

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);做题时我们要从局部往整体写,先写一个大的框架,再添细节,但我很明显还没有习惯这么做,以后做题要注意这方面的培养,这样会让你做题更加简单。
 
 
 

转载于:https://www.cnblogs.com/lbyj/p/5676054.html

你可能感兴趣的文章
录制终端信息并回放
查看>>
JS中window.event事件使用详解
查看>>
ES6深入学习记录(一)class方法相关
查看>>
《BI项目笔记》用Excel2013连接和浏览OLAP多维数据集
查看>>
C语言对mysql数据库的操作
查看>>
SQL Server 数据库备份
查看>>
INNO SETUP 获得命令行参数
查看>>
Charles抓取https请求
查看>>
LAMP环境搭建
查看>>
C语言的变量的内存分配
查看>>
clientcontainerThrift Types
查看>>
链接全局变量再说BSS段的清理
查看>>
hdu 1728 逃离迷宫
查看>>
HTML5与CSS3权威指南之CSS3学习记录
查看>>
docker安装部署
查看>>
AVL树、splay树(伸展树)和红黑树比较
查看>>
多媒体音量条显示异常跳动
查看>>
运算符及题目(2017.1.8)
查看>>
React接入Sentry.js
查看>>
ssh自动分发密匙脚本样板
查看>>