注:本人英语很渣,题目大意大多来自百度~=0=
题目大意
农民约翰需要抓住他的牛,他和他的牛在一条直线上(估计是一维生物),约翰在N (0 ≤ N ≤ 100,000)处,他的牛在 K (0 ≤ K ≤ 100,000) ,约翰下次可以从x移动到x+1或者x-1或者2*x的地方,问约翰最少需要多少步才能找到他的牛。
用BFS可以解决~ 不过需要剪枝 不然会MLE
值得一提的一点是步数不要用结构体保存 或许是我剪枝不够好 用结构体保存会MLE
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cstdlib>
#include <cmath>
#include <cctype>
#define N 200010
using namespace std; bool maps[N];//用来判断此点约翰有没有走过
int a, b, step[N];//a, b 为分别为N, K, //step[i]用来保存约翰走到i点时用了几步 (注 : 不要用结构体保存步数, 不然有可能MLE) void BFS()
{
int q1 = a;
maps[a] = true;
queue<int>q;
q.push(q1); while(!q.empty()) {
int q2 = q.front();
q.pop();
if(q2 == b) {//找到之后输出走了几步
printf("%d\n", step[q2]);
return ;
}
//约翰向走 -1 只有此时他的坐标为正数才会走
int x = q2 - ;
if(!maps[x] && q2 > ) {
maps[x] = true;
q1 = x;
step[q1] = step[q2] + ;
q.push(q1);
}
//由于约翰向后走只能 -1 所以只在q2 < b时才向前走
if(q2 < b){
x = q2 + ;
if(!maps[x]) {
maps[x] = true;
q1 = x;
step[q1] = step[q2] + ;
q.push(q1);
}
x = q2 * ;
if(!maps[x]) {
maps[x] = true;
q1 = x;
step[q1] = step[q2] + ;
q.push(q1);
}
} }
} int main()
{
while(~scanf("%d %d", &a, &b)){
memset(maps, , sizeof(maps));
BFS();
}
return ;
}