Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 43401 Accepted: 13512
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 43401 | Accepted: 13512 |
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
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.
我跳我跳我跳跳跳
Time Limit: 1000MS Memory limit: 65536K
题目描述
有一条直线,上有n个点,编号从0到n-1。当小A站在s点处,每次可以往前跳到s+1,也可以往前跳到s-1(当s-1 >= 0时),也可以调到2*s处。现在问小A最少跳多少次才能跳到点e处。
输入
多组输入。每组输入两个整数s,e(0 <= s,e <= 100,000)。n趋于无穷大。
输出
输出小A从s跳到e的最小次数。
示例输入
5 17
示例输出
4
提示
来源
解题报告
比赛的时候根本没有想到是bfs解题的,还以为是背包呢,bfs一维。。。
多组输入每次都是忘了数组清零的节奏。。。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct node
{
int x,num;
}q[1000000];
int s,e;
int v[1000000];
void bfs()
{
node now,next;
int t=0,f=0;
now.x=s;
now.num=0;
q[f++]=now;
v[now.x]=1;
while(t<f)
{
now=q[t++];
//printf("x =%d,num =%d\n",now.x,now.num);
if(now.x==e)
{
printf("%d\n",now.num);
return ;
}
next.x=now.x+1;
if(next.x>=0&&next.x<300000&&v[next.x]!=1 )
{
next.num=now.num+1;
q[f++]=next;
v[next.x]=1;
}
next.x=now.x-1;
if(next.x>=0&&next.x<300000&&v[next.x]!=1)
{
next.num=now.num+1;
q[f++]=next;
v[next.x]=1;
}
next.x=now.x*2;
if(next.x>=0&&next.x<300000&&v[next.x]!=1)
{
next.num=now.num+1;
q[f++]=next;
v[next.x]=1;
}
}
}
int main(){
while(~scanf("%d%d",&s,&e)){
memset(v,0,sizeof(v));
bfs();
}
}