HDU2717-Catch That Cow (BFS入门)

时间:2023-03-09 07:53:27
HDU2717-Catch That Cow (BFS入门)

题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2717

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14880    Accepted Submission(s): 4495

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.

题意:
从a走到b,你可以向前走一步,向后走一步或者走a*2步,求最少多少步
 #include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int v[],t[];
int main()
{
int n,a,b,i,f;
while(scanf("%d%d",&a,&b)!=EOF)
{
memset(t,,sizeof(t));
memset(v,,sizeof(v));
queue<int > q;
q.push(a);
v[a]=;
if(a==b)
{
printf("0\n");
continue;
}
while(!q.empty())
{
int ll=q.front(),r=ll-,l=ll+,z=ll*;
q.pop();
//printf("ll=%d\n",ll);
if(z>=&&z<=&&!v[z])
{
q.push(z);
v[z]=v[ll]+;
// printf("v[z]=%d z=%d\n",v[z],z);
}
if(l>=&&l<=&&!v[l])
{
q.push(l);
v[l]=v[ll]+;
// printf("v[l]=%d l=%d\n",v[l],l);
}
if(r>=&&r<=&&!v[r])
{
q.push(r);
v[r]=v[ll]+;
// printf("v[r]=%d r=%d\n",v[r],r);
} if(l==b||r==b||z==b)
{ break;
} } printf("%d\n",v[b]-); }
return ; }