zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    【作业7】完成调查问卷
    用博客园第一周
    讲座观后感
    调查问卷
    第十一周·前端学习笔记--正则表达式
    调查问卷
    思维导图
    讲座心得1
    第一次作业(8.学习进度表)
    第一次作业(7.问卷调查)
  • 原文地址:https://www.cnblogs.com/Friends-A/p/10324394.html
Copyright © 2011-2022 走看看