POJ-3278(BFS)

时间:2023-03-09 13:16:35
POJ-3278(BFS)

题目:

                                                                                                                                                         Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
     

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 - 1 or + 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

分析:题目大意是在数轴上给定任意起点n、终点k,对任意的点坐标x每次有3种走法:x-1,x+1,2*x。每走一次花费时间为1minute,问从n到k最少需要花费多少时间?

      该题是最短路径问题,于是可以用BFS搜索,每次往三个方向BFS,直到到达k,每走一步记录当前时间。

//simonPR
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=;
int n,k,vis[maxn];
struct catche{
int site,times; //记录点和所花的时间。
};
queue<catche> q;
void init();
void init(){
while(!q.empty())
q.pop();
memset(vis,,sizeof(vis));
}
int bfs(int n,int k);
int bfs(int n,int k){
if(n==k) return ;
catche now,news,start;
start.site=n;
start.times=;
q.push(start); //将起点入队列。
vis[n]=;
while(!q.empty()){
int ts;
now=q.front();
q.pop();
for(int i=;i<;i++){ //分三个方向BFS。
if(i==) ts=now.site-;
else if(i==) ts=now.site+;
else ts=*now.site;
if(ts>maxn||vis[ts]==) continue; //如果已经访问过了或超出数据范围则跳过。
if(ts==k) return now.times+; //到达终点K,返回时间。
if(vis[ts]==) //更新点信息,并将新点入队列。
{
vis[ts]=;
news.site=ts;
news.times=now.times+;
q.push(news);
}
}
}
}
int main()
{
scanf("%d%d",&n,&k);
init(); //初始化。
int ans=bfs(n,k);
printf("%d\n",ans);
return ;
}