Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 47033 | Accepted: 14770 |
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?
John农民终于知道那个逃跑的母牛去哪了,并且想赶紧给抓回来。他在点N(0 ≤ N ≤ 100,000),牛在点K (0 ≤ K ≤ 100,000) ,他们都在同一个数轴上。John有两种移动方式:走路和远距离传送。
走路:FJ可以从X移动到X-1和X+1在一分钟内
远距离传送:FJ可以从X移动到2*X在一分钟内
牛,还没意识到自己被跟踪了,根本不动,John多久才能逮到牛?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
Source
#include <stdio.h>
#include <string.h>
struct Point{
int dis;
int step;
};
int main(void){
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int head = 0, tail = 1;
int visit[200004];
int n, k;
struct Point fifo[200004];
scanf("%d%d", &n, &k);
memset(visit, 0, sizeof(visit));
visit[n] = 1;
//printf("%d%d\n", n, k);
fifo[head].dis = n;
fifo[head].step = 0;
while(head <= tail){
struct Point curr = fifo[head];
if (curr.dis == k){
printf("%d\n", fifo[head].step);
break;
}
if ((0 <= curr.dis - 1) && (visit[curr.dis - 1] == 0)){
fifo[tail].dis = curr.dis - 1;
fifo[tail++].step = curr.step + 1;
visit[curr.dis - 1] = 1;
printf("tail = %d\n", tail);
}
if ((curr.dis <= k) && (visit[curr.dis + 1] == 0)){//here not corr.dis + 1 <= k;
fifo[tail].dis = curr.dis + 1;
fifo[tail++].step = curr.step + 1;
visit[curr.dis + 1] = 1;
}
if ((curr.dis <= k) && (visit[curr.dis * 2] == 0)){//here not corr.dis * 2 <= k;
fifo[tail].dis = curr.dis * 2;
fifo[tail++].step = curr.step + 1;
visit[curr.dis * 2] = 1;
}
head ++;
}
return 0;
}