原题:
传送门
题意:
一维坐标,给定farmer位置n,cow位置k,求farmer到cow的最短走法。其中farmer有三种走法:1.从x到x+1 2.从x到x-1 3.从x到2x
思路:
bfs搜索即可,注意多组输入,注意搜索方向不能先是2x的,因为x=0时,也会step[0] = step[0] + 1;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
queue<int> q;
int n, k;
int step[100007];
int bfs(int x) {
q.push(x);
while (!q.empty()) {
int u=q.front();q.pop();
if (u == k) {
return step[u];
}
if (u-1>=0 && step[u-1] == 0) {q.push(u-1);step[u-1]=step[u]+1;}
if (u+1<=100000 && step[u+1] == 0) {q.push(u+1);step[u+1]=step[u]+1;}
if (2*u<=100000 && step[2*u] == 0) {q.push(2*u);step[2*u]=step[u]+1;}
}
return -1;
}
void init() {
while (!q.empty())
q.pop();
for (int i=0;i<100007;i++) {
step[i] = 0;
}
}
int main()
{
while (cin>>n>>k) {
init();
cout<<bfs(n)<<endl;
}
return 0;
}