Catch That Cow
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
Hint
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
思路:
这道题数据量也不大,同样可以暴搜,三种情况,+1,-1和*2,一起搜就好了,不过可以把没必要的剪枝做一些小小的优化
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
#include<set>
#include<vector>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#define ll long long
using namespace std;
const int maxn = (int)2e5 + 10;
bool vis[maxn];
struct node
{
int x,step;
friend bool operator < (node a,node b)
{
return a.step > b.step;
}
};
void bfs(int n,int k)
{
int ans = -1;
memset(vis,0,sizeof(vis));
priority_queue<node> que;
vis[n] = 1;
node p,p2;
p.x = n,p.step = 0;
que.push(p);
while (!que.empty())
{
p = que.top();
p2 = p;
que.pop();
if (p.x == k)
{
ans = p.step;
break;
}
if (!vis[p.x + 1] && p.x + 1 <= k)
{
p2.x = p.x + 1;
vis[p2.x] = 1;
p2.step = p.step + 1;
que.push(p2);
}
if (!vis[p.x - 1] && p.x - 1 >= 0)
{
p2.x = p.x - 1;
vis[p2.x] = 1;
p2.step = p.step + 1;
que.push(p2);
}
if (p.x <= k && !vis[p.x * 2])
{
p2.x = p.x * 2;
vis[p2.x] = 1;
p2.step = p.step + 1;
que.push(p2);
}
}
printf("%d\n",ans);
}
int main()
{
int n,k;
scanf("%d %d",&n,&k);
bfs(n,k);
return 0;
}