cf.295.B Two Buttons (bfs)

本文介绍了一个使用BFS算法解决特定设备操作问题的方法,目标是通过最少的操作次数将显示数值从初始值n调整到目标值m。详细阐述了算法实现步骤,包括使用pair和set的数据结构,以及如何通过蓝色按钮减一和红色按钮乘二来达到最终目标。
 Two Buttons
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Sample test(s)
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 #include<stdio.h>
 2 #include<queue>
 3 #include<set>
 4 using namespace std;
 5 int n , m ;
 6 
 7 int main ()
 8 {
 9    //freopen ("a.txt" , "r" , stdin) ;
10     while (~ scanf ("%d%d" , &n , &m)) {
11         queue <pair <int , int> > q ;
12         set <int> s ;
13         q.push ( {n , 0} ) ;
14         while (!q.empty ()) {
15             pair <int , int> p = q.front () ;
16             q.pop () ;
17             if (p.first <= 0 )
18                 continue ;
19             if (p.first == m) {
20                 printf ("%d\n" , p.second) ;
21                 break ;
22             }
23             else {
24                 s.insert (p.first) ;
25                 if (s.count (p.first - 1 ) == 0 ) {
26                         q.push ( {p.first - 1 , p.second + 1 } ) ;
27                 }
28                 if (p.first < m && s.count (p.first * 2) == 0 ) {
29                     q.push ( {p.first * 2 , p.second + 1 } ) ;
30                 }
31             }
32         }
33     }
34     return 0 ;
35 }
View Code

我是用bfs(看别人的),见识了set 和 pair 的用法。

There is, however, an even faster solution. The problem can be reversed as follows: we should get the number n starting from m using the operations "add 1 to the number" and "divide the number by 2 if it is even".

转载于:https://www.cnblogs.com/get-an-AC-everyday/p/4335756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值