Catch That Cow POJ - 3278
题目描述
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.
大致题意
农夫John要抓回一头牛,他们位置都在x轴上,在单位时间John可以前进一步x+1或者后退一步x-1,或者前进x步即2*x,现在分别告诉你John的位置和牛的位置,问需要抓到牛的最少时间。
思路
bfs求最优解
下面是代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include<sstream>
#include<ctime>
using namespace std;
struct node
{
int x,step; //定义结构体node记录坐标x和已用单位时间
};
int n,k;
queue<node> Q; //bfs所用队列
int f[200005]; //用一维数组f来记录某坐标点是否已经走过
void bfs()
{
int x,step;
while(!Q.empty())
{
node tmp=Q.front(); //取队首元素
Q.pop(); //出队列
x=tmp.x;
step=tmp.step;
if(x==k) //已经到达牛所在的位置,结束bfs,输出结果
{
cout<<step;
return;
}
if(x>=1&&!f[x-1]) //边界判断,判断该位置是否已经走过
{
node temp;
f[x-1]=1;
temp.x=x-1;
temp.step=step+1;
Q.push(temp);
}
if(x<=k&&!f[x+1])
{
node temp;
f[x+1]=1;
temp.x=x+1;
temp.step=step+1;
Q.push(temp);
}
if(x<=k&&!f[x*2])
{
node temp;
f[x*2]=1;
temp.x=2*x;
temp.step=step+1;
Q.push(temp);
}
}
}
int main()
{
cin>>n>>k;
memset(f,0,sizeof(int)); //初始化
f[n]=1;
node a;
a.x=n;
a.step=0;
Q.push(a);
bfs();
return 0;
}