博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Catch That Cow(BFS广搜)
阅读量:5254 次
发布时间:2019-06-14

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

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.
 
 
广搜的基本例题:
 
1 #include
2 #include
3 #include
4 #include
5 using namespace std; 6 struct point 7 { 8 int x;///记录位置 9 int count;///记录步数10 };11 queue
q;12 struct point s,now,t;13 int vis[200000];///假设FJ开始的位置就是100000,那么变化两倍之后就是20000014 int bfs(int n,int m)15 {16 int j;17 while(!q.empty())18 {19 q.pop();20 }///清空队列21 memset(vis,0,sizeof(vis));22 vis[s.x]=1;23 q.push(s);24 while(!q.empty())25 {26 t=q.front();27 if(t.x==m)28 return t.count;29 for(j=0; j<3; j++)30 {31 now=t;32 if(j==0)33 {34 now.x=now.x+1;35 }36 else if (j==1)37 {38 now.x=now.x-1;39 }40 else if(j==2)41 {42 now.x=now.x*2;43 }44 now.count++;45 if(now.x==m)46 {47 return now.count;48 }49 if(now.x>=0&&now.x<=200000&&vis[now.x]==0)50 {51 vis[now.x]=1;52 q.push(now);53 }54 }55 q.pop();56 }57 return 0;///二者开始的位置相同58 }59 int main()60 {61 int n,m,ans;62 while(scanf("%d%d",&n,&m)!=EOF)63 {64 s.x=n;65 s.count=0;66 ans=bfs(n,m);67 printf("%d\n",ans);68 }69 return 0;70 }

反思:这道题和之前的那一道剑客救公主那一道题一样,不仅仅需要考虑题意之中的搜索方式,还要考虑搜索不到或者起始位置与终止位置相同等特殊情况,该去如何设置被调函数,该去返回一个什么样的值,这两道题都是因为这一点使我wa了好多次,引以为戒。

转载于:https://www.cnblogs.com/wkfvawl/p/8906745.html

你可能感兴趣的文章
ServerSocket和Socket通信
查看>>
css & input type & search icon
查看>>
jQuery插件开发详细教程
查看>>
Crontab 在linux中的非常有用的Schedule Jobs
查看>>
ProxySQL Scheduler
查看>>
源代码的下载和编译读后感
查看>>
Kafka学习笔记
查看>>
Octotree Chrome安装与使用方法
查看>>
用CALayer实现下载进度条控件
查看>>
Windows 环境下基于 Redis 的 Celery 任务调度模块的实现
查看>>
趣谈Java变量的可见性问题
查看>>
C# 强制关闭当前程序进程(完全Kill掉不留痕迹)
查看>>
ssm框架之将数据库的数据导入导出为excel文件
查看>>
语音识别中的MFCC的提取原理和MATLAB实现
查看>>
验证组件FluentValidation的使用示例
查看>>
0320-学习进度条
查看>>
解决windows系统的oracle数据库不能启动ora-00119和ora-00130的问题
查看>>
ip相关问题解答
查看>>
MetaWeblog API Test
查看>>
反弹SHELL
查看>>