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.
http://poj.org/problem?id=3278
题意:
三种走法,+1,-1,*2,
tip
Z = max(2*K,N);
如果目标在右侧 不会走过目标2倍,因为往回走只能减1,浪费时间
如果目标在左侧 不会超过起始点,不会再往右边走了哈
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
const int maxn = 200010;
using namespace std;
int N,K,Z;
bool vis[maxn];
int step[maxn];
void init(){
memset(vis,false,sizeof(vis));
Z = max(2*K,N);
}
void sov(){
queue<int>q;
q.push(N);
step[N] = 0;
vis[N] = true;
while(!q.empty()){
int tmp = q.front();
q.pop();
if(tmp == K){
printf("%d\n",step[K]);
return;
}
int x ;
for(int i = 0 ; i < 3; i++){
if(i == 0) x = tmp+1;
if(i == 1) x = tmp-1;
if(i == 2) x = tmp*2;
if(x >=0 && x <= Z&&vis[x] == false){
vis[x] = true;
q.push(x);
step[x] = step[tmp]+1;
}
}
}
return;
}
int main(){
while(~scanf("%d%d",&N,&K)){
init();
sov();
}
}