Codeforces 520B:Two Buttons(思维,好题)

题目链接:http://codeforces.com/problemset/problem/520/B

题意

给出两个数n和m,n每次只能进行乘2或者减1的操作,问n至少经过多少次变换后能变成m

思路

在百度之前用了各种方法,dfs,递推什么的能用的全用了,最后都WA在了第七组

百度了一下,看到了大佬们的代码震精了!!!竟然只有一行!!

用逆推,把从n变成m转换成从m变成n。

如果m是偶数那么m一定是通过上一步乘2的操作变来的,如果是奇数,那么一定是通过上一步减一变来的。最后当m小于n的时候,停止循环,令循环过程中得到的操作次数加上n和m的差值就是正确结果了

AC代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
const double E=exp(1);
const int maxn=1e6+10;
using namespace std;
int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	int n,m;
	cin>>n>>m;
	int res=0;
	while(n<m)
	{
		if(m%2)
			m++;
		else
			m/=2;
		res++;
	}
	cout<<res+n-m<<endl;
	return 0;
}
原文地址:https://www.cnblogs.com/Friends-A/p/10324394.html