您的位置:首页 > 其它

【原】 POJ 3278 Catch That Cow BFS单源无权图最短距离 解题报告

2010-11-08 19:46 435 查看
 

http://poj.org/problem?id=3278

 

方法:
单源无权图最短距离,即BFS
该问题只需要求得某两点间的最短距离,所以不必求得所有节点的最短距离,一旦处理了目的地点,即可返回结果

 

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.

 

[code][code] #include <stdio.h>


#include <iostream>


#include <vector>


#include <queue>


 


using namespace std ;


 


typedef vector<int> Table ;


const int INF = 0x7fffffff ;


const int MaxRange = 100000 ;


 


void run3278()


{


int i ;


int n,k ;


int range ;


int adjArr[3] ;


int vertex,adV ;


int curDist ;


queue<int> Q ;


 


scanf("%d%d", &n,&k) ;


 


//这里容易出错:Table开得太小。


//题意中已经给出最大的节点标号,所以按此数初始化Table


Table T( MaxRange+1,INF ) ;  //初始化table有MaxRange个无穷值




//BFS


T
= 0 ; //起始点距离为0


Q.push(n) ;


while( !Q.empty() )


    {


    vertex = Q.front() ;


    Q.pop() ;


    curDist = T[vertex] ;


 


    //得到结果


    if( vertex == k )


   {


   printf( "%d\n" , T[vertex] ) ;


   return ;


   }


 


    //***得到节点v的邻接点,可能是v-1、v+1、2*v


    //超出范围的设为-1


    if( vertex-1<0 )


   adjArr[0] = -1 ;


    else


   adjArr[0] = vertex-1 ;


 


    if( vertex+1>MaxRange )


   adjArr[1] = -1 ;


    else


   adjArr[1] = vertex+1 ;


 


    if( vertex*2>MaxRange )


   adjArr[2] = -1 ;


    else


   adjArr[2] = vertex*2 ;


    //***


 


    //对未经处理的邻接点进行处理


    for( i=0 ; i<3 ; ++i )


   {


   if( ( adV=adjArr[i] ) == -1 )


  continue ;


   if( T[adV] == INF )


  {


  T[adV] = curDist+1 ;


 


  //得到结果


  if( adV == k )


 {


 printf( "%d\n" , T[adV] ) ;


 return ;


 }


 


  Q.push(adV) ;


  }


   }


}


}

[/code]
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: