抓住那头牛

描述

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0≤N≤100000),牛位于点K(0≤K≤100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟

2、从X移动到2*X,每次移动花费一分钟

假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

输入描述

两个整数,N和K。

输出描述

一个整数,农夫抓到牛所要花费的最小分钟数。

用例输入 1 

5 17

用例输出 1 

4
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=1e5+10;
int n,k;
bool f[N];
struct node{
	int x;
	int cnt;
};
queue<node> q;
int main(){
	cin>>n>>k;
	if(n==k){
		cout<<0;
		return 0;
	}
	q.push(node{n,0});
	while(!q.empty()){
		node t=q.front();
		int a,b,c;
		a=t.x-1;
		b=t.x+1;
		c=t.x*2;
		if(a==k||b==k||c==k){
			cout<<t.cnt+1;
			return 0;
		}
		if(a>=0 && !f[a]){
			q.push(node{a,t.cnt+1});
			f[a]=1;
		}
		if(b<=100000 && !f[b]){
			q.push(node{b,t.cnt+1});
			f[b]=1;
		}
		if(c<=100000 && !f[c]){
			q.push(node{c,t.cnt+1});
			f[c]=1;
		}
		q.pop();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值