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
Output
Sample Input
5 17
Sample Output
4
Hint
题目大意:给出起始位置与牛所在的位置,你只能进行2种操作:向前或向后移动一步,或者从当前位置到达2*n处。求到达目标位置的最小操作次数。
思路:以前写的时候总以为是DFS,然后各自WA 各种T。考虑最优操作,采用BFS队列处理。
代码如下:
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<set>
#include<map>
#include<string>
using namespace std;
int f[2]={-1,1};
struct fun{
int x;
int t;
}p,p1;
int bfs(int x,int k)
{
queue<fun>q1,q2;
p.x=x;p.t=0;
int vis[100005]={0};
q1.push(p);
while(!q1.empty())
{
p=q1.front();q1.pop();
if(p.x==k)
return p.t;
for(int i=0;i<2;i++)
{
p1.x=p.x+f[i];
p1.t=p.t+1;
if(p1.x>=0&&p1.x<=100000&&vis[p1.x]==0)
{
vis[p1.x]=1;
q1.push(p1);
}
}
p1.x=p.x*2;p1.t=p.t+1;
if(p1.x>=0&&p1.x<=100000&&vis[p1.x]==0)
{
vis[p1.x]=1;
q1.push(p1);
}
}
return 0;
}
int main()
{
int n,m;
scanf("%d%d",&n,&m);
printf("%d\n",bfs(n,m));
return 0;
}