1. 程式人生 > >C - Catch That Cow ~ [kuangbin帶你飛]專題一 簡單搜尋

C - Catch That Cow ~ [kuangbin帶你飛]專題一 簡單搜尋

 

農夫知道一頭牛的位置,想要抓住它。農夫和牛都於數軸上 ,農夫起始位於點 N(0<=N<=100000) ,牛位於點 K(0<=K<=100000) 。農夫有兩種移動方式: 1、從 X移動到 X-1或X+1 ,每次移動花費一分鐘 2、從 X移動到 2*X ,每次移動花費一分鐘 假設牛沒有意識到農夫的行動,站在原地不。最少要花多少時間才能抓住牛?

Input

一行: 以空格分隔的兩個字母: NK

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;
}