Catch That Cow
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 [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.[/hint]
题目大意:农夫的牛丢了,现在给农夫的位置N,和牛的位置K。一维坐标。现在假如牛不动,农夫去找牛,有两种走路方式,一种x-1,和x+1用时1。
一种2*x,用时1 。求最短时间。
简单广搜,搜索入门题。
这道题要标记找过的不能找了,超出范围的不能找了,否则会时间超限。
#include<bits/stdc++.h>///Catch That Cow
using namespace std;
int to[2]={1,-1};
int a,b,sum;
int vis[100000];
struct place
{
int x,time;
};
int check(place k)
{
if(k.x<0||k.x>100000||vis[k.x]==1)
return 0;
return 1;
}
int bfs(place n)
{
place m,next;
queue<place>w;
w.push(n);
while(!w.empty())
{
m=w.front();
w.pop();
if(m.x==b)
return m.time;
for(int i=0;i<2;i++)
{
next.x=m.x+to[i];
next.time=m.time+1;
if(next.x==b)
return next.time;
if(check(next))
{
w.push(next);
vis[next.x]=1;
}
}
next.x=m.x*2;
next.time=m.time+1;
if(next.x==b)
return next.time;
if(check(next))
{
w.push(next);
vis[next.x]=1;
}
}
return 0;
}
int main()
{
int i,j,t;
place x1;
while(~scanf("%d %d",&a,&b))
{
memset(vis,0,sizeof(vis));
x1.x=a;
x1.time=0;
vis[x1.x]=1;
sum=0;
sum=bfs(x1);
printf("%d\n",sum);
}
return 0;
}