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.
#include <iostream>
#include <vector>
#include <queue>
5:
namespace std ;
7:
int> Table ;
int INF = 0x7fffffff ;
int MaxRange = 100000 ;
11:
void run3278()
13: {
int i ;
int n,k ;
int range ;
int adjArr[3] ;
int vertex,adV ;
int curDist ;
int> Q ;
21:
, &n,&k) ;
23:
//这里容易出错:Table开得太小。
//题意中已经给出最大的节点标号,所以按此数初始化Table
//初始化table有MaxRange个无穷值
27:
//BFS
//起始点距离为0
30: Q.push(n) ;
while( !Q.empty() )
32: {
33: vertex = Q.front() ;
34: Q.pop() ;
35: curDist = T[vertex] ;
36:
//得到结果
if( vertex == k )
39: {
, T[vertex] ) ;
return ;
42: }
43:
//***得到节点v的邻接点,可能是v-1、v+1、2*v
//超出范围的设为-1
if( vertex-1<0 )
47: adjArr[0] = -1 ;
else
49: adjArr[0] = vertex-1 ;
50:
if( vertex+1>MaxRange )
52: adjArr[1] = -1 ;
else
54: adjArr[1] = vertex+1 ;
55:
if( vertex*2>MaxRange )
57: adjArr[2] = -1 ;
else
59: adjArr[2] = vertex*2 ;
//***
61:
//对未经处理的邻接点进行处理
for( i=0 ; i<3 ; ++i )
64: {
if( ( adV=adjArr[i] ) == -1 )
continue ;
if( T[adV] == INF )
68: {
69: T[adV] = curDist+1 ;
70:
//得到结果
if( adV == k )
73: {
, T[adV] ) ;
return ;
76: }
77:
78: Q.push(adV) ;
79: }
80: }
81: }
82: }