我是靠谱客的博主 大方信封,最近开发中收集的这篇文章主要介绍C - 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 - 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.

题解:这是一个广搜,最重要的是每一次搜索到的数字都要标记起来,避免重复搜索,然后要规定范围,要不会超出限制,也有可能会超内存。

代码:

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
struct node
{
int num,step;
}h[10];
int nu[10000000];
void kk(struct node s,int ed)
{
queue<node>Q;
Q.push(s);
nu[s.num]=1;
while(Q.size())
{
s=Q.front();
Q.pop();
if(s.num==ed)
{
printf("%dn",s.step);
break;
}
int t;
struct node p;
for(t=0;t<3;t++)
{
p=s;
if(t==0)
{
p.num-=1;
}
else if(t==1)
{
p.num+=1;
}
else if(t==2)
{
p.num=p.num*2;
}
if(p.num>=0&&p.num<=1000000&&nu[p.num]==0)
{
nu[p.num]=1;
p.step=s.step+1;
Q.push(p);
}
}
}
}
int main()
{
int a;
scanf("%d %d",&h[1].num,&a);
h[1].step=0;
kk(h[1],a);
return 0;
}

 

最后

以上就是大方信封为你收集整理的C - Catch That Cow的全部内容,希望文章能够帮你解决C - Catch That Cow所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部