POJ 3278 Catch That Cow(BFS,板子题)
Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 88732 | Accepted: 27795 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
Source
1 #include<iostream> 2 #include <algorithm> 3 #include <stdio.h> 4 #include <string.h> 5 #include<queue> 6 #define MAX 100001 7 using namespace std; 8 queue<int> q;//使用前需定义一个queue变量,且定义时已经初始化 9 bool visit[MAX];//访问空间 10 int step[MAX]; //记录步数的数组不能少 11 bool bound(int num)//定义边界函数 12 { 13 if(num<0||num>100000) 14 return true; 15 return false; 16 } 17 int BFS(int st,int end) 18 { 19 queue<int> q;//使用前需定义一个queue变量,且定义时已经初始化 20 int t,temp; 21 q.push(st);//进队列 22 visit[st]=true; 23 while(!q.empty())//重复使用时,用这个初始化 24 { 25 t=q.front();//得到队首的值 26 q.pop();//出队列,弹出队列的第一个元素,并不会返回元素的值 27 for(int i=0;i<3;++i) //三个方向搜索 28 { 29 if(i==0) 30 temp=t+1; 31 else if(i==1) 32 temp=t-1; 33 else 34 temp=t*2; 35 if(bound(temp)) //越界 36 continue; 37 if(!visit[temp])//访问空间未被标记 38 { 39 step[temp]=step[t]+1; 40 if(temp==end) 41 return step[temp]; 42 visit[temp]=true;//标记此点 43 q.push(temp);//将temp元素接到队列的末端; 44 } 45 } 46 } 47 } 48 int main() 49 { 50 int st,end; 51 while(scanf("%d%d",&st,&end)!=EOF) 52 { 53 memset(visit,false,sizeof(visit));//visit数组进行初始化操作 54 if(st>=end) 55 cout<<st-end<<endl; 56 else 57 cout<<BFS(st,end)<<endl; 58 } 59 return 0; 60 }
作 者:Angel_Kitty
出 处:https://www.cnblogs.com/ECJTUACM-873284962/
关于作者:阿里云ACE,目前主要研究方向是Web安全漏洞以及反序列化。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信我
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!
欢迎大家关注我的微信公众号IT老实人(IThonest),如果您觉得文章对您有很大的帮助,您可以考虑赏博主一杯咖啡以资鼓励,您的肯定将是我最大的动力。thx.

我的公众号是IT老实人(IThonest),一个有故事的公众号,欢迎大家来这里讨论,共同进步,不断学习才能不断进步。扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码),个人QQ和微信的二维码也已给出,扫描下面👇的二维码一起来讨论吧!!!

欢迎大家关注我的Github,一些文章的备份和平常做的一些项目会存放在这里。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述