Catch That Cow

CatchThatCow算法解析
本文介绍了一个名为CatchThatCow的问题,这是一个经典的搜索问题。问题描述了农夫约翰如何使用步行和传送两种方式来抓住逃跑的奶牛。文章通过示例详细解释了如何使用广度优先搜索算法解决该问题,并提供了一段实现此算法的C++代码。

Catch That Cow

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 113   Accepted Submission(s) : 46
Problem 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
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
 
 1 #include<stdio.h>
 2 #include<queue>
 3 #include<string.h>
 4 using namespace std;
 5 const int MAXN=100010;
 6 int visit[MAXN];
 7 int now[3];
 8 int N,K,step,t;
 9 void bfs(){
10     queue<int>dl;
11     dl.push(N);
12     visit[N]=1;
13     if(N!=K){
14     while(!dl.empty()){
15         t=dl.size();
16         step++;
17         while(t--){
18             now[0]=dl.front()+1;
19             now[1]=dl.front()-1;
20             now[2]=dl.front()*2;
21             dl.pop();
22             for(int i=0;i<3;i++){
23                 if(now[i]==K)return;
24                 if(now[i]>0&&now[i]<=100000&&!visit[now[i]]){//醉了,少了个0,错了n次;;;;; 
25                     visit[now[i]]=1;dl.push(now[i]);
26                 }
27             }
28         }
29     }
30 }
31 }
32 int main(){
33     while(~scanf("%d%d",&N,&K)){
34         memset(visit,0,sizeof(visit));
35         step=0;
36         bfs();
37         printf("%d\n",step);
38     }
39     return 0;
40 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值