SGU 126. Boxes --- 模拟
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时,以后的都是重复开始的那两个数字,所以前面不能实现题目的操作的话,后面不可能实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | #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; } |
作者:北岛知寒
出处:https://www.cnblogs.com/crazyacking/p/3825753.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?