BFS --- 模板题
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 36079 | Accepted: 11123 |
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
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.
【题目来源】
#include<iostream> #include<cstring> #include<queue> using namespace std; int N,K; struct now { int x; int step; }; bool vis[1000010]; int BFS(int x) { int tx; now ans,tp; queue<now> que; ans.x=x,ans.step=0; vis[x]=true; que.push(ans); while(!que.empty()) { tp=que.front(); que.pop(); tx=tp.x+1; //no.1 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } tx=tp.x-1; //no.2 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } tx=tp.x*2; //no.3 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } } } int main() { while(cin>>N>>K) { if(N==K) { cout<<"0"<<endl; continue; } memset(vis,false,sizeof(vis)); cout<<BFS(N)<<endl; } return 0; }
当然还可以剪枝一下,比如说:如果人的坐标大于牛的坐标,这时就只需要做-1这一步就可以了。
作者:北岛知寒
出处:https://www.cnblogs.com/crazyacking/p/3748504.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个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——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?