• 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
    ",ans);
        }
        return 0;
    }
    

      

  • 相关阅读:
    U盘启动盘恢复为普通盘
    TP框架模板中ifelse
    TP框架中多条件筛选
    日期选择器:jquery datepicker的使用
    配置本地环境,让内网可访问
    FlexSlider插件的详细设置参数
    CentOS+Nginx+PHP+MySQL详细配置(图解)
    Linux 服务器环境启动
    javascript自定义浏览器右键菜单
    强大实用的jQuery幻灯片插件Owl Carousel
  • 原文地址:https://www.cnblogs.com/crazyacking/p/3825753.html
Copyright © 2020-2023  润新知