Codeforces Round #295 (Div. 2) B. Two Buttons

B. 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.

题意:

给两个数,n,m,让n通过给点两种走步方法等于m

对n可以有两种操作:

1. 减1

2.乘2

我只会BFS。。。

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<math.h>
 4 #include<stdlib.h>
 5 #include<string.h>
 6 #include<queue>
 7 using namespace std;
 8 const int MAX=2e4+4;
 9 const int MIN=0;
10 struct stu
11 {
12     int num;
13     int step;
14 }start,one,two;
15 queue<struct stu>q;
16 bool vis[MAX+5];
17 void bfs(int n,int m)
18 {
19     memset(vis,false,sizeof(vis));
20     start.num = n;
21     start.step = 0;
22     vis[n]=1;
23     q.push(start);
24     while(!q.empty())
25     {
26         one=q.front();
27         two=q.front();
28         q.pop();//删队首
29         one.num*=2;
30         one.step++;
31         two.num-=1;
32         two.step++;
33         if(one.num==m)
34         {
35             printf("%d
",one.step);
36             break;
37         }
38         if(two.num==m)
39         {
40             printf("%d
",two.step);
41         }
42         if(one.num>0 && one.num<MAX && !vis[one.num])
43         {
44             q.push(one);
45             vis[one.num]=1;
46         }
47         if(two.num>0 && two.num<MAX && !vis[two.num])
48         {
49             q.push(two);
50             vis[two.num]=1;
51         }
52     }
53 }
54 
55 int main()
56 {
57     int n,m;
58     while(~scanf("%d%d",&n,&m))
59     {
60         if(n>m)
61         {
62             printf("%d
",n-m);
63         }
64         else if(n==m)
65         printf("0
");
66         else
67         {
68             bfs(n,m);
69         }
70     }
71     return 0;
72 }
原文地址:https://www.cnblogs.com/xuesen1995/p/4332523.html