520B - Two Buttons

链接:

https://codeforces.com/problemset/problem/520/B

题意:

给一个n,一个m,

可以做以下操作:

1、让n*2;

2、让n-1;

最少多少步让n变成,m;

输入

4 6

输出量

2

输入

10 1

输出量

9

解:

数据量一组,n,m<=10000

dfs,后面其实看了一下到佬的写法,bfs一层一层搜,或者直接逆着推导,让m变成n就行

我的dfs是搜索每个数字状态的最优,不是最优的就避免进入dfs占用时间,通过一个int数组标记最优;

反复搜索到没有新最优产生,输出ans。

实际代码:

#include<iostream>
#include<limits.h>
using namespace std;
int sz[100000];
int Ans=1000000000;
void dfs(int n,int m,int ans)//m是目标,n是当前 
{
	sz[n]=ans;
	//cout<<n<<" "<<m<<endl;
	if(n>20000||n<=0) return;
	if(n==m)
	{
		if(ans<Ans)
		{
			Ans=ans;
		}
	}
	if(sz[n*2]>(ans+1)&&n<m) dfs(n*2,m,ans+1);
	if(sz[n-1]>ans+1)dfs(n-1,m,ans+1);
}
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=0;i<=20000;i++)
	{
		sz[i]=INT_MAX;
	}
	dfs(n,m,0); 
	cout<<Ans<<endl;
}

/*
int main()
{
	int n,m;
	cin>>n>>m;
	int ans=0;
	for(;m!=n;) 
	{
		if(m<n) m++;//n比m大,只能-1,反向思考,m+1 
		else if(m%2) m++;//m能不能被整除,只能先加一 
		else m/=2;//能整除,除二配对n 
		ans++;
	}
	cout<<ans<<endl;
}
*/

限制:

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值