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.
Sample test(s)
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.
思路:如果n大于m,不能使用红色按钮,很容易看出,步数就是n-m。
如果n比m小,如果m是偶数的话,m/2,如果m是奇数,m+1,这样一直循环判断n是不是还比m小,不符合就跳出循环,进入第一个如果。
贪心的思想:其实如果m比n大 ,n肯定有*2,问题就是先减再乘还是先乘再减。这是正常人的思路。
但是反过来推,如果m是奇数,一定是减一造成的,如果是偶数,更快的办法是*2造成的。就这么寻欢做下去知道遇到m=n。
#include<iostream>
using namespace std;
#include<cmath>
int cnt = 0;
int main()
{
int n,m;
cin>>n>>m;
if(n>=m) cout<<n-m<<endl;
else
{
while(m>n)
{
if(m%2==0) m /= 2;
else m++;//开始写的是m-- 既然倒着推应该是m++
cnt++;
}
cnt = cnt+(n-m);
cout<<cnt<<endl;
}
return 0;
}
第二种方法,用记忆化搜索的方法
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int dfs(int x);
int dp[20005],vis[20005];
int n,m;
int main()
{
cin>>n>>m;
memset(dp,0x3f3f3f,sizeof(dp));
memset(vis,0,sizeof(vis));
cout<<dfs(n)<<endl;
return 0;
}
int dfs(int x)
{
if(x<=0)return 9999999;
if(x>=m)
{
dp[x] = x-m;
// cout<<x<<' '<<dp[x]<<endl;
return dp[x];
}
if(vis[x])
{
// cout<<x<<' '<<dp[x]<<endl;
return dp[x];
}
vis[x] = 1;
dp[x] = min(dfs(x-1),dfs(x*2))+1;//不是很明白为什么不是dp[x] = min(dfs(x+1),dfs(x/2))+1
// cout<<x<<' '<<dp[x]<<endl;
return dp[x];
}