Catch That Cow POJ - 3278
农夫约翰得知了一头逃亡奶牛的位置,想要立即抓住她。他起始于数轴上的点N(0 ≤ N ≤ 100,000),而奶牛位于同一条数轴上的点K(0 ≤ K ≤ 100,000)。农夫约翰有两种移动方式:步行和传送。
* 步行:约翰可以从任意点X在一分钟内移动到X-1或X+1的位置
* 传送:约翰可以从任意点X在一分钟内移动到2×X的位置
如果奶牛没有察觉被追踪而始终保持静止,农夫约翰需要多长时间才能抓住它?
输入
第1行:两个用空格分隔的整数:N和K
输出
第1行:农夫约翰抓住逃亡奶牛所需的最短时间(以分钟为单位)
样例
Inputcopy | Outputcopy |
---|---|
5 17 | 4 |
提示
农夫约翰抓住逃亡奶牛的最快路径是:5-10-9-18-17,共耗时4分钟。
代码
#include <stdio.h>
#include <string.h>#define MAXN 100005
#define Que que[tail][0] = tx, que[tail][1] = fstep+1, vis[tx] = 1, tail++
int vis[MAXN], que[MAXN * 30][2];
int n, k;
int is(int x) {if (x >= 0 && x <= 100000 && vis[x] == 0) return 1; // 注意! x >= 0return 0;
}
int main()
{scanf("%d%d", &n, &k);int head = 0, tail = 1;memset(vis, 0, sizeof vis), memset(que, 0, sizeof que);que[0][0] = n, que[0][1] = 0, vis[n] = 1;while (head < tail){int fx = que[head][0], fstep = que[head][1], tx; head++;if (fx == k) {printf("%d", fstep); return 0;}// x - 1tx = fx - 1;if (is(tx)) Que;// x + 1tx = fx + 1;if (is(tx)) Que;// x * 2;tx = fx * 2;if (is(tx)) Que;}return 0;
}