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.
Source
USACO 2007 Open Silver
题意:
FJ要抓奶牛。
开始输入N(FJ的位置)K(奶牛的位置)。
FJ有三种移动方法:1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
问FJ抓到奶牛的最少时间。PS:奶牛是不会动的。
思路:
首先 ,这是一道关于队列的题目 我们可用队列的知识求解
具体思路,首先我们定义两个数组step和position,step存的是步数,position代表位置,step[n]表示走到n这个点需要走几步,所以S[n+1 or n-1 or n2]=s[n]+1;
那么,我们就开始进行查找 。
第一步,我们把农夫的位置n入队,然后对n+1,n-1,n2的位置进行判断如果没有走过(就是position[n+1 or n-1 or n2]==0)则把position[n+1 or n-1 or n2]赋值为一,step[n+1 or n-1 or n2]=step[n]+1.如果为终点则退出
第二步,把n+1,n-1,n2入队,把队首出队,然后对出队后的队首判断重复上步骤一。
注意 , 以下代码的入队和出队等操作代码都是手写的。
代码
#include<stdlib.h>
#include"抓.cpp"
int find(int *step,int *weizhi,int n,int m);
int main()
{
int n,m;
int step[10001]={0};
int weizhi[10001]={0};
scanf("%d%d",&n,&m);
weizhi[n]=1;
int end=find(step,weizhi,n,m);
printf("%d",end);
}
int find(int *step,int *weizhi,int n,int m)
{
LinkQueue L;
InitQueue(&L);
EnQueue(&L,n);
while(1)
{
int x;
GetQHead(L,&x);
if(x+1==m||x-1==m||x*2==m)
{
int end=step[x]+1;
return end;
}
else
{
if(x-1>=0&&weizhi[x-1]==0)
{
weizhi[x-1]=1;
EnQueue(&L,x-1);
step[x-1]=step[x]+1;
}
if(x+1<=10000&&weizhi[x+1]==0)
{
weizhi[x+1]=1;
EnQueue(&L,x+1);
step[x+1]=step[x]+1;
}
if(x*2<=10000&&weizhi[x*2]==0)
{
weizhi[x*2]=1;
EnQueue(&L,x*2);
step[x*2]=step[x]+1;
}
int T;
DeQueue(&L,&T);
}
}
}