农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 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分钟.
思路 :本题直接dfs会超时,所以应该进行减枝优化(多谢wbt提供) ;
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
#include<string>
#include<stack>
#define ll long long
using namespace std;
int N,K;
struct Node
{
int x;
int step;
Node(){}
Node(int xx,int ss) : x(xx) , step(ss) {}
};
int book[1000000] ;
int bfs(int x,int step)
{
queue<Node> Q;
Q.push(Node(x,step));
book[x] = 1;
while(!Q.empty())
{
Node u = Q.front() ;
Q.pop() ;
if(u.x == K )
{
return u.step;
}
for(int i=0 ; i<3 ; i++)
{
if(i==2 && u.x>K)
{
continue;
}
if(i==0)
{
int xx=u.x + 1;
int ss=u.step + 1 ;
if(book[xx]==0&& xx>0)
{
book[xx]=1;
Q.push(Node(xx,ss));
}
}
if(i==1)
{
int xx=u.x - 1;
int ss=u.step + 1 ;
if(book[xx]==0 && xx>0)
{
book[xx]=1;
Q.push(Node(xx,ss));
}
}
if(i==2)
{
int xx=u.x + u.x;
int ss=u.step + 1 ;
if(book[xx]==0&&xx>0)
{
book[xx]=1;
Q.push(Node(xx,ss));
}
}
}
}
return -1;
}
int main()
{
cin>>N>>K;
if(N>K)
{
cout<<N-K<<endl;
return 0;
}
cout<<bfs(N,0)<<endl;
return 0;
}