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

本文介绍了一道算法题目,目标是最少次数操作使初始数值通过乘2或减1的方式达到目标数值。采用广度优先搜索算法(BFS)解决该问题,并提供了完整的C++实现代码。
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\n",one.step);
36             break;
37         }
38         if(two.num==m)
39         {
40             printf("%d\n",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",n-m);
63         }
64         else if(n==m)
65         printf("0\n");
66         else
67         {
68             bfs(n,m);
69         }
70     }
71     return 0;
72 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值