CodeForces - 520B 按钮 [广度优先搜索/贪心]

Posted 晓风微微

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces - 520B 按钮 [广度优先搜索/贪心]相关的知识,希望对你有一定的参考价值。

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.

Example

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<bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5 long long a,n,m;
 6 scanf("%lld%lld",&n,&m);
 7 a=0;
 8 while(n<m)
 9 {
10 if(m%2==1)
11  m++;
12 else
13  m=m/2;
14 a++;
15 }
16 printf("%lld\n",a+n-m);
17 }

做法二:

BFS

BFS训练题里有一道类似的题

需要注意的两点:

一是把控好下界,不要出现比0小的情况

二是把控好一个合适的上界,不要叫程序无限制的一直往大的离谱的数字上去搜索

做好以上两点剪枝,就没有问题了

代码:

#include<bits/stdc++.h>
using namespace std;
#define read(x) scanf("%lld",&x)
#define out(x) printf("%lld",&x)
#define cfread(x) scanf("%I64d",&x)
#define cfout(x) printf("%I64d",&x)
#define mian main
#define min(x,y) (x<y?x:y)
#define max(x,y) (x<y?y:x)
#define f(i,p,q,t) for(i=p;i<q;i+=t)
#define MAXN 110000
#define inf 0x3f3f3f3f
#define mem(x,t) memset(x,t,sizeof(x));
#define T true
#define F false
#define def -1*inf
map<int,int> v;
queue< pair<int,int> > team;//队列 
int main(){
    int l,r;
    cin>>l>>r;
    team.push(make_pair(l,0));
    v[l] = 1;
    int ans = -1;
    while(!team.empty()){
        pair<int,int> x = team.front();
        team.pop();
        if(x.first==r){
            ans = x.second;
            break;
        }
        pair<int,int> nx = make_pair(2*x.first,x.second+1);
        if(!(v[nx.first]||nx.first>3*r)){
            team.push(nx);
            v[nx.first]=1;
        }
        nx = make_pair(x.first-1,x.second+1);
        if(!(v[nx.first]||nx.first<0)){
            team.push(nx);
            v[nx.first]=1;
        }
    }
    cout<<ans;
//  return 0;
    return 0;
}

 

以上是关于CodeForces - 520B 按钮 [广度优先搜索/贪心]的主要内容,如果未能解决你的问题,请参考以下文章

打CF,学算法——二星级CF 520B Two Buttons

CodeForces-920E Connected Components? 广度搜索 判断联通 大量数据下重复点的删除

广度优先和深度优先算法

python-广度优先搜索

CodeForces 731E Funny Game

数据结构C语言版 图的广度优先遍历和深度优先遍历 急急急 会查重