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?
The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .
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.
4 6
2
10 1
9
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.
题目还是很容易看懂的:给你两个按钮red和blue,输入n和m,要求n变到m最少需要几步。一个按钮可以进行减一的操作,另一个按钮可以将n乘以2的操作。这样可以想一下,当n<<m的时候,我可以希望n能够变到m*1/2的状态,然后只要一步操作就够了。以此类推,n变到m的1/4,1/8……这样的操作数可以达到最少。所以先在进行递归判断之前进行上述的处理,就可以出来了。
#include<stdio.h>
#include<math.h>
int t,f;
void buttons(int n,int m,int cnt)
{
// printf("%d ",n);
if(f)return;
t=cnt;
if(n==m){f=1;return;}
if(n*2<=m)buttons(n*2,m,cnt+1);
if(n*2>m){
if(fabs(n*2-m)<=fabs((n-1)*2-m))buttons(n*2,m,cnt+1);
else buttons(n-1,m,cnt+1);
}
}
int main()
{
int n,m,i,j;
while(scanf("%d%d",&n,&m)!=EOF)
{
f=0;
t=0;
if(m<=n)t=n-m;
else
{
while(n*2<m)
{if(m%2==1){m=m/2+1;t=t+2;}
else {m=m/2;t=t+1; }
}// printf("m=%d ",m);
buttons(n,m,t);
}
printf("%d\n",t);
}
return 0;
}