Catch That Cow
题目描述:
Farmer John 已获悉一头逃亡奶牛的位置,并希望立即抓住她。 他从数轴上的点 N (0 ≤ N ≤ 100,000) 开始,而奶牛在同一数轴上的点 K (0 ≤ K ≤ 100,000) 处。 Farmer John 有两种交通方式:步行和传送。
- 步行:FJ可以在一分钟内从任意点 X 移动到点 X - 1 或 X + 1
- 传送:FJ可以在一分钟内从任意点 X 移动到点 2 × X。
如果母牛没有意识到它的追赶,根本不动,农夫约翰需要多长时间才能找回它?
思路解析:
简单的bfs就可以了,每次把三个可能会到的点入队,如果到终点就结束。
AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cmath>
#include <queue>
using namespace std;
const int N = 100000;
int n, k;
int f[N+10];
queue<int>q;
int main(){
scanf("%d%d", &n, &k);
q.push(n);
while(!q.empty()){
int t = q.front();
q.pop();
if(t == k){
printf("%d\n",f[t]);
break;
}
if(t - 1 >= 0 && !f[t - 1]) f[t - 1] = f[t] + 1, q.push(t - 1);
if(t + 1 <= N && !f[t + 1]) f[t + 1] = f[t] + 1, q.push(t + 1);
if(t << 1 <= N && !f[t << 1]) f[t << 1] = f[t] + 1, q.push(t << 1);
}
return 0;
}