Two Buttons(思维 好题!!!codeforces520b)

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)/~

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值