CodeForces - 520B Two Buttons、BFS、:【翻译题解】

B. Two Buttons

Description

Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.

Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?

Input

The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .

Output

Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n.

Examples

input

4 6

output

2

input

10 1

output

9
Note
In the first example you need to push the blue button once, and then push the red button once.

In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.

给定一个自然数,有两种操作,
1.将数字乘 2。
2.将数字减去 1。
如果某次操作后数字不为正数,则终止。
一开始你拥有的是数字 n 。
你的目标是得到数字 m 。为了获得这个结果,他最少需要做多少次操作?

写这道题的原因还是想记一记BFS模板,加深一下印象。

AC代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 1e4 + 10;
int n, m, step[maxn];
bool vis[maxn];
queue <int> q;
int bfs(int st, int en) {
	int u, v;
	q.push(st);
	step[st] = 0, vis[st] = 1;
	while (!q.empty()) {
		u = q.front();
		q.pop();
		for (int i = 1; i <= 2; i++) {
			if (i == 1)
				v = u - 1;				// 后退一步
			else
				v = u * 2;				// 乘以2
			if (v < 0 || v >= maxn)		//  判断是否越界
				continue;
			if (!vis[v]) {				// 如果满足条件,入队,记录步数
				q.push(v);
				step[v] = step[u] + 1;
				vis[v] = 1;
			}
			if (v == en)				// 判断是否到达目的点
				return step[v];
		}
	}
}
int main() {
	cin >> n >> m;
	if (n >= m)	cout << n - m << endl;
	else
		cout << bfs(n, m) << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值