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?
The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .
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.
4 6
2
10 1
9
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.
bfs就过了
#include <stdio.h>
#include <string.h>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;
int n , m;
struct node{
int x;
int step;
}pre, nex;
int v[10005];
void bfs() {
queue<node> q;
pre.x = n;
pre.step = 0;
v[n] = 1;
q.push(pre);
while(!q.empty()) {
nex = q.front();
q.pop();
if(nex.x == m) {
printf("%d\n",nex.step);
return ;
}
int dx;
for(int i = 0; i < 2; i++) {
if(i == 0) {
if(nex.x > m) {
dx = nex.x - 1;
if(v[dx] == 0 && dx >= 1) {
v[dx] = 1;
pre.x = dx;
pre.step = nex.step + 1;
q.push(pre);
}
}
else {
dx = nex.x*2;
if(v[dx] == 0 && dx >= 1) {
v[dx] = 1;
pre.x = dx;
pre.step = nex.step + 1;
q.push(pre);
}
dx = nex.x-1;
if(v[dx] == 0 && dx >= 1) {
v[dx] = 1;
pre.x = dx;
pre.step = nex.step + 1;
q.push(pre);
}
}
}
}
}
}
int main() {
memset(v, 0, sizeof(v));
scanf("%d%d",&n,&m);
bfs();
return 0;
}
最小步数变换数字
本文介绍了一种使用广度优先搜索算法(BFS)解决如何从初始正整数n通过最少的操作步骤达到目标数m的方法。操作包括点击红色按钮使数字翻倍或蓝色按钮使数字减一。文中提供了一个C++实现示例。
1738

被折叠的 条评论
为什么被折叠?



