1. 程式人生 > >CodeForces - 520B 按鈕 [廣度優先搜索/貪心]

CodeForces - 520B 按鈕 [廣度優先搜索/貪心]

pan 上界 ace pty index sep dev log down

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 按鈕 [廣度優先搜索/貪心]