HDU2717 Catch That Cow BFS

来源:互联网 发布:php 如何分割数组 编辑:程序博客网 时间:2024/05/18 23:54

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.

BFS  注意n=k   

 //第一次写,木有经验,将就将就~~~~~

 

#include<iostream>using namespace std;#include<stdio.h>#include<string.h>#define MAX 100002int queue[2*MAX];int step[2*MAX];int judge(int y){    if(y>=2*MAX||y<0||step[y]!=0)  return 0;    else   return 1;//step[y]!=0表示已经访问过}int bfs(int n,int k){    int x,front=0,rear=0;    if(n==k)  return 0;    queue[front++]=n;    while(rear<front)    {        x=queue[rear++];//x 表示当前访问点        if(x+1==k||x-1==k||2*x==k)  return step[x]+1;        if(judge(x-1))  {step[x-1]=step[x]+1; queue[front++]=x-1;}        if(judge(x+1))  {step[x+1]=step[x]+1; queue[front++]=x+1;}        if(judge(x*2))  {step[x*2]=step[x]+1; queue[front++]=x*2;}    }    return 0;}int main(){    int n,k;    while(~scanf("%d%d",&n,&k))    {        memset(step,0,sizeof(step));        printf("%d\n",bfs(n,k));    }    return 0;}