抓住那头牛

【问题描述】
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?
【输入形式】
两个整数,N和K
【输出形式】
一个整数,农夫抓到牛所要花费的最小分钟数
【样例输入】
5 17
【样例输出】
4

#include<iostream>
#include<queue>
#include<math.h>
using namespace std;
int main() {
	int times[200000];
	for (int j = 0; j < 200000; j++) {
		times[j] = -1;
	}
	queue<int>cash;
	int farmer, cattle, i = 1, pow_number = 0;
	cin >> farmer >> cattle;
	cash.push(farmer);
	while (times[cattle] == -1) {
		int number = cash.front();
		cash.pop();
		if (farmer > cattle) {
			times[cattle] = farmer - cattle;
		}
		else {
			if (number - 1 >= 0) {
				if (times[number - 1] > i || times[number - 1] == -1) {
					times[number - 1] = i;
				}
				cash.push(number - 1);
			}
			if (times[number + 1] > i || times[number + 1] == -1) {
				times[number + 1] = i;
			}
			cash.push(number + 1);
			if (number * 2 < 200000) {
				if (times[number * 2] > i || times[number * 2] == -1) {
					times[number * 2] = i;
				}
				cash.push(number * 2);
			}
			pow_number++;
			if (pow_number >= pow(3, i - 1)) {
				i++;
				pow_number = 0;
			}
		}
	}
		
	cout << times[cattle];
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值