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时,以后的都是重复开始的那两个数字,所以前面不能实现题目的操作的话,后面不可能实现。

 

 

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值