<传送门>

126. Boxes

time limit per test: 0.25 sec. 
memory limit per test: 4096 KB

There are two boxes. There are A balls in the first box, and B balls in the second box (0 < A + B < 2147483648). It is possible to move balls from one box to another. From one box into another one should move as many balls as the other box already contains. You have to determine, whether it is possible to move all balls into one box.

Input

The first line contains two integers A and B, delimited by space.

Output

First line should contain the number N - the number of moves which are required to move all balls into one box, or -1 if it is impossible.

Sample Input

Sample Output

2 6

Sample Output

2

【题目大意】

简单地说就是:给你两个数a和b,现在你可以“将大数-小数,小数变为原来2倍”,问你能否在有限次的操作后使得其中哟个数等于0,另外一个数为原来两个数的和。

若可能,输出步数;不可能输出-1.

【题目分析】

一开始的时候,我用每次都使得a为大数,b为小数,但是这样会出现循环,因为每次都维护他们的前后大小,势必会造成循环。

如果我们只是一开始维护一次大小关系,以后就不管他了,这样当b增加到>=a的时候,还不满足一个为0的条件,那么就说明不可能实现这样的操作。

证明过程如下:

give two numbers: a and b;(a!=b)

a=max(a,b);    b=min(a,b);

重复:  a=a-b;  b=b+b;    当b大于等于a时,以后的都是重复开始的那两个数字,所以前面不能实现题目的操作的话,后面不可能实现。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; int a,b; int sovle()
{
if(a == b) return 1;
else if(a == 0 || b == 0) return 0;
int cnt = 1;
int tmp;
if(a < b)
{
tmp = a;
a = 2*tmp;
b = b - tmp;
}
else if(a > b)
{
tmp = b;
b = 2*tmp;
a = a - tmp;
} if(a > b)
{
tmp = a;
a = b;
b = tmp;
}
if(b%a != 0) return -1;
else{
while(a < b)
{
tmp = a;
a = tmp + tmp;
b = b - tmp;
cnt ++;
if(a == b)
break;
}
if(a == b) return cnt + 1;
else return -1;
}
} int main()
{
while(scanf("%d%d",&a,&b) != EOF)
{
int ans = sovle();
printf("%d\n",ans);
}
return 0;
}

  

最新文章

  1. Android test---SL4A
  2. oracle存储过程中的if...elseif...else用法
  3. Hibernate关联关系配置(一对多、一对一和多对多)
  4. Docker进入主流,PaaS大有可为(转)
  5. lintcode :Binary Tree Preorder Traversal 二叉树的前序遍历
  6. cocos2d-x 锚点,位置==》动手实验记录 多动手... :)
  7. scala学习笔记:理解并行集合par
  8. js - get-the-value-from-the-url-parameter(可以在非模态对话框中使用)
  9. SlidingMenu侧换菜单的导入
  10. 型牌男装施春蕾:分拆让马云对淘宝定位更清晰--互联网 -- CCTIME飞象网
  11. php中的时区设置
  12. 分针网—每日分享: 怎么轻松学习JavaScript
  13. 备忘录《一》基于cookie使用拦截器实现客户每次访问自登陆一次
  14. git常用命令二、:git stash
  15. 在linux 上安装ansible
  16. winform程序中chart图的使用经验(chart图的更新)
  17. 搭建真正的zookeeper集群
  18. python-给微信好友自动发送天气预报和每日一句
  19. [LeetCode&amp;Python] Problem 202. Happy Number
  20. C++中int与string的相互转换【转】

热门文章

  1. Laravel 解决blade模板转义html标签问题
  2. 入门平衡树: Treap
  3. A1016 | 磨人的大模拟
  4. Technocup 2020 Elimination Round 3题解
  5. SpringMVC相关试题
  6. web程序设计关于我们
  7. getaddrinfo工作原理分析
  8. CentOS7安装及配置vsftpd (FTP服务器FTP账号创建以及权限设置)
  9. CSRF的防御
  10. easyui datagrid生成序号列formatter