Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 39887 | Accepted: 12412 |
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
Source
#include <stdio.h>
#include <queue>
#include <string.h>
#define N 200030
using namespace std;
struct Node{
int k;
int s;
};
int n, k;
bool visit[N];
int bfs();
queue<Node>q;
int main()
{
Node nw;
while(scanf("%d%d", &n, &k)!=EOF) {
while(!q.empty()) q.pop();
memset(visit, 0, sizeof(visit));
if(n == k)
printf("0\n");
else{
nw.k = n;
nw.s = 0;
visit[n] = 1;
q.push(nw);
int ans = bfs();
printf("%d\n", ans);
}
}
return 0;
}
int bfs()
{
Node cur, nw;
while(1){
cur.k = q.front().k;
cur.s = q.front().s + 1;
q.pop();
if(cur.k - 1 >= 0 && !visit[cur.k - 1]){
nw = cur;
nw.k -= 1;
if(nw.k == k)
return nw.s;
visit[nw.k] = 1;
q.push(nw);
}
if(cur.k + 1 <= k && !visit[cur.k + 1]){
nw = cur;
nw.k += 1;
if(nw.k == k)
return nw.s;
visit[nw.k] = 1;
q.push(nw);
}
if(cur.k * 2 <= k && !visit[cur.k * 2]){
nw = cur;
nw.k *= 2;
if(nw.k == k)
return nw.s;
visit[nw.k] = 1;
q.push(nw);
}
}
return 0;
}