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.
Examples
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.
题目应该挺好懂得,就是红色按钮就是乘以2,蓝色按钮就是减1。问最少多少步才能使n变成m
这个题目可以模拟,也可以动态规划,可以贪心,可以dfs(深搜)。我用的后两种方法。
我们想一下,m可能是前一步减1,也有可能前一步乘以2得到的。由m退回去。就是如果m为偶数。就除以二。如果m为奇数,就m++。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int n,m;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==m) cout<<0<<endl;
else if(n>m) cout<<n-m<<endl;
else
{
int res=0;
while(n<m)
{
if(m%2) m++;
else m/=2;
res++;
}
cout<<res+n-m<<endl;
}
}
}
除了这个之后,还有dfs,就是记忆化搜索加剪枝,
代码如下:
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
const int maxx=1e4+10;
int n,m;
int ans[maxx];//用来储存到达每一个数的最小步数
void dfs(int x,int y,int cnt)
{
if(x<=0) return ;//x小于0的时候就返回
if(ans[x]<cnt) return ;//剪枝,如果原来到达这个数的步数小于cnt,就返回
ans[x]=cnt;
if(x>y)//如果x>y,就只有一个一个减了
{
dfs(y,y,cnt+x-y);
return ;
}
if(x==y) //如果两个相等,就比较原先记录的和现在的步数,取小的那一个。
{
ans[x]=min(cnt,ans[x]);
return ;
}
dfs(x*2,y,cnt+1);//乘以2
dfs(x-1,y,cnt+1);//减一
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==m) cout<<0<<endl;
else if(n>m) cout<<n-m<<endl;
else
{
memset(ans,inf,sizeof(ans));
ans[n]=0;
dfs(n,m,0);
cout<<ans[m]<<endl;
}
}
}
记忆化+剪枝真的很重要,,多加练习
努力加油a啊,(o)/~