题目要求:
某知名翻译家:
稻草人发现了一头残血逃走的牛头,他想立即抓住它。稻草人在点N,牛头在点K,稻草人可以直线去抓它(0≤n≤100000)(0≤k≤100000)
稻草人有两个位移技能:闪现和传送。
召唤师技能:闪现:可以在一分钟内从任意点X移动到点X-1或X+1
召唤师技能:传送:可以在一分钟内从任意点X移动到点2X。
假设牛头掉线了,农夫约翰至少需要多长时间才能抢到人头?
抓人思路:
题目给的输入例子中位置分别是5 和 17,然后最快是4分钟抓到。
这时优秀的稻草人脑中闪过许多种抓人的方法。
其中最快的是5->4->8->16->17.或5->10->9->18->17.
思路和广度优先搜索差不多,可以通过队列来解答。
经过多次WA,有几个细节要处理一下:
①、评论区看的,题目不太清楚,要多组数据才能通过
②、不走回头路,于是声明了vis数组存放,记得清零
③、if条件后面要习惯加else!if条件后面要习惯加else!if条件后面要习惯加else!重要的话复制三遍!
#include<iostream>
#include<queue>
using namespace std;
int N, K;
struct point {
int X;
int T;
};
bool vis[200050];
int main() {
while (cin >> N >> K) {
memset(vis, 0, sizeof(vis));
point a;
a.X = N;
a.T = 0;
queue<point> que;
que.push(a);
while (!que.empty()) {
point temp = que.front();
que.pop();
//判断
if (temp.X == K) {
cout << temp.T << endl;
}
else {
//往后退
if (temp.X - 1 >= 0 && vis[temp.X - 1] == 0) {
point t = temp;
t.X--;
t.T++;
que.push(t);
vis[temp.X - 1] = 1;
}
//往前走
if (temp.X < K && vis[temp.X + 1] == 0) {
point t = temp;
t.X++;
t.T++;
que.push(t);
vis[temp.X + 1] = 1;
}
//乘2
if (temp.X < K && vis[temp.X * 2] == 0) {
point t = temp;
t.X *= 2;
t.T++;
que.push(t);
vis[temp.X * 2] = 1;
}
}
}
}
return 0;
}
最终,稻草人被牛头反杀,end。