POJ 3278 Catch That Cow(BFS,板子题)

时间:2022-06-29 07:21:52

Catch That Cow

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 88732   Accepted: 27795

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.

Source

题目链接:http://poj.org/problem?id=3278
题意:有一个农民和一头牛,他们在一个数轴上,牛在k位置保持不动,农户开始时在n位置。设农户当前在M位置,每次移动时有三种选择:1.移动到M-1;2.移动到M+1位置;3.移动到M*2的位置。问最少移动多少次可以移动到牛所在的位置。所以可以用广搜来搜索这三个状态,直到搜索到牛所在的位置。
分析:BFS的板子题,用队列做,第一次学队列,感觉自己好弱啊!现在才学,算法真的好难学,学了又怕不会用,现在不敢学太快了!
下面每一步代码我都给出了详细解释,一看就懂!
 #include<iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include<queue>
#define MAX 100001
using namespace std;
queue<int> q;//使用前需定义一个queue变量,且定义时已经初始化
bool visit[MAX];//访问空间
int step[MAX]; //记录步数的数组不能少
bool bound(int num)//定义边界函数
{
if(num<||num>)
return true;
return false;
}
int BFS(int st,int end)
{
queue<int> q;//使用前需定义一个queue变量,且定义时已经初始化
int t,temp;
q.push(st);//进队列
visit[st]=true;
while(!q.empty())//重复使用时,用这个初始化
{
t=q.front();//得到队首的值
q.pop();//出队列,弹出队列的第一个元素,并不会返回元素的值
for(int i=;i<;++i) //三个方向搜索
{
if(i==)
temp=t+;
else if(i==)
temp=t-;
else
temp=t*;
if(bound(temp)) //越界
continue;
if(!visit[temp])//访问空间未被标记
{
step[temp]=step[t]+;
if(temp==end)
return step[temp];
visit[temp]=true;//标记此点
q.push(temp);//将temp元素接到队列的末端;
}
}
}
}
int main()
{
int st,end;
while(scanf("%d%d",&st,&end)!=EOF)
{
memset(visit,false,sizeof(visit));//visit数组进行初始化操作
if(st>=end)
cout<<st-end<<endl;
else
cout<<BFS(st,end)<<endl;
}
return ;
}