【CF简单介绍】

提交链接:Two Buttons

题面:

B. Two Buttons
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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.

Sample test(s)
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.

解题:

法一:

一開始看到这题,感觉似曾相识。感觉可能能够写,最初的想法是这种。n>=m。直接输出n-m。当n<m时。m若为偶数除2,m为奇数+1除以2。一直分解m到1。并记录这个过程中m分解的过程。然后将n减到近期的m分解过程中的m上。感觉非常不靠谱。纯瞎想。结果别人敲了一下说是对的。只是不是必需这么复杂,循环 m是偶数  除以2 计数值+1 。m是奇数 加一除以2  计数值+2  直到m<n 。 最后计数值加上n-m就好了 尽管不知道为什么这样就对。可是感觉是让减法尽量早减,这样就能够降低减法的次数。

代码:

#include <iostream>
using namespace std;
int main()
{
int n,m,cnt=0,t,ans=0,last;
cin>>n>>m;
if(n>=m)cout<<n-m<<endl;
else
{
while(m>n)
{
if(m%2==0)
{
ans++;
m/=2;
}
else
{
m=(m+1)/2;
ans+=2;
}
}
ans+=(n-m);
cout<<ans<<endl;
}
return 0;
}

法二:

看了一篇题解。说是spfa爆搜,顿时给跪了。感觉好奇怪。我也没看详细题解,想了一下。是不是建一张图,10000个数,减法由x到x-1建立一条权值为1的边。乘法由n到2*n建立一条权值为1的边,最后仅仅要搜索n到m的最短路就好了。

这是我自己的想法。感觉非常巧妙,可是不会超复杂度吗?然而边不是矩阵存储的,由于10000个数。最多不会超过20000条边。

最新文章

  1. Storm进程通信机制
  2. android 关于appcompat v7出错问题与解决
  3. 将对象转换成Dictionary 字典
  4. Computer Transformation(hdoj 1041)
  5. junit initializationError和找不到或无法加载主类
  6. Java Mac电脑配置java环境,JAVA IDE eclipse开发svn使用
  7. tornado SSL 证书获取与服务器配置
  8. Mysql运算符与函数(胖胖老师)
  9. Android之人脸识别
  10. Codeforces Round #536 (Div. 2) F 矩阵快速幂 + bsgs(新坑) + exgcd(新坑) + 欧拉降幂
  11. 几种优化方法的整理(SGD,Adagrad,Adadelta,Adam)
  12. BIEE启动关闭服务(转)
  13. 趣谈StateServer在Web Garden,Web Farm下的使用
  14. SQL中 ALL 和 ANY 区别的
  15. springMVC的controller返回值
  16. Wifi模块的工作原理
  17. es6 - 回调深渊
  18. 每日英语:Vender Assault Shines Ugly Light on China&#39;s Urban Enforcers
  19. [pixhawk笔记]11-Windows下PX4代码查看
  20. thinkphp5 No input file specified.

热门文章

  1. Sql生成不重复的数字
  2. solr深分页,游标操作分页,解决性能问题
  3. JDBC性能优化
  4. eclipse中添加maven
  5. 华登区块狗系统APP开发
  6. Java基础——异常
  7. STL++?pb_ds平板电视初步探索
  8. mysql的密码管理、mysql初始密码查找、密码修改、mysql登录
  9. buf.writeInt16BE()函数详解
  10. SocketServer 网络服务框架