2021-9-2 Two Buttons

难度 1400

题目 Codeforces:

B. Two Buttons
time limit per test
2 seconds
memory limit per test

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.

 

题目解析

本题就是标准的bfs,具体直接看代码

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<queue>
 4 using namespace std;
 5 typedef long long ll;
 6 int n, m,x[10005];
 7 bool book[10005];
 8 queue<int>q;
 9 int bfs()
10 {
11     q.push(n);
12     x[n] = 0;
13     book[n] = 1;
14     while (!q.empty())
15     {
16         int y,temp = q.front();
17         q.pop();
18         for (int i = 0; i < 2; i++)
19         {
20             if (i)y = temp - 1;
21             else y = temp * 2;
22             if (y < 0 || y >= 10005)continue;
23             if (!book[y])
24             {
25                 q.push(y);
26                 x[y] = x[temp] + 1;
27                 book[y] = 1;
28             }
29             if (y == m)return x[y];
30         }
31     }
32 }
33 int main()
34 {
35     cin >> n >> m;
36     if (n >= m)cout << n - m << "\n";
37     else cout << bfs() << "\n";
38     return 0;
39 }

 

2021-9-2 Two Buttons

上一篇:编译型与解释型的联系与区别


下一篇:题解 P3174 [HAOI2009]毛毛虫