【原】 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]
相关文章推荐
- 【原】 POJ 3126 Prime Path 筛素数+BFS单源无权最短路径 解题报告
- POJ 3278解题报告(C语言版)//Catch That Cow
- POJ_3278 Catch That Cow 解题报告
- 【解题报告】 POJ 3714 Raid -- 点对最小距离 + 分治法
- 2011.11.3 poj1860 Currency Exchange 单源最短路径 Bellman-Ford算法 解题报告
- 2011.11.10 poj1062,poj2253,poj1125 单源最短路径 解题报告
- POJ 3278 解题报告
- POJ-3278___抓奶牛——解题报告 BFS
- 【原】 POJ 1035 Spell checker 编辑距离 解题报告
- POJ-3278 Catch That Cow 解题报告
- POJ - 3278 Catch That Cow解题报告
- poj解题报告——3278
- POJ - 3414 Pots解题报告(输出路径的bfs)
- POJ 1012 Joseph解题报告
- POJ 1011 Sticks 解题报告
- poj1142 解题报告
- poj 2367 & poj 1094 分析&解题报告(拓扑排序入门)
- POJ 1477 解题报告
- poj 3728 LCA+并查集 解题报告
- poj1173 解题报告