C - Catch That Cow(bfs的简单应用)
Catch That Cow
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
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.
题目分析:给定农夫约翰的和母牛的位置,其中农夫可以进行两种操作:
*步行:农夫约翰可以在一分钟内从任意一个点移动到X-1或X+1
*心灵传送:农夫约翰可以在一分钟内从任意一个点移动到2个点。而母牛不动,则对于农夫约翰需要多长时间才能找回他?
解题思路:此题也是求最早寻找时间,我们则可以利用bfs搜索。此题易解。
AC代码:
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<memory.h>
using namespace std;
int n,k; //n代表农夫约翰的位置,k代表母牛的位置。
const int maxn=1e5+5;
bool visited[maxn]; //辅助数组,判断是否被访问过
int result[maxn]; //存储步数
void bfs(int n,int k)//通过bfs来寻求最短路径。
{
queue<int> Q; //利用队列
int head,temp;
head=n;
visited[n]=true;
Q.push(head);
while(!Q.empty())
{
head=Q.front();
Q.pop();
for(int i=0;i<3;i++) //三种步骤
{
temp=head;
if(i==0)temp+=1;
else if(i==1)temp-=1;
else temp*=2;
if(temp<0||temp>maxn)continue; //判断是否出界
if(!visited[temp]) //判断是否被访问过
{
result[temp]=result[head]+1;
Q.push(temp);
visited[temp]=true;
}
if(temp==k){cout<<result[temp]<<endl;return;}
}
}
return ;
}
int main()
{
while(cin>>n>>k)
{
if(n>=k){cout<<n-k<<endl;continue;} //考虑n大于等于k的情况,此时n只能往后减一
memset(visited,0,sizeof(visited));
memset(result,0,sizeof(result));
bfs(n,k);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!