zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    【笑话】程序员和青蛙公主
    C#获取实体类属性名和值 | 遍历类对象
    VS2010 C# 使用DirectSound
    Serializing CTreeCtrl to / from a text file
    DirectX编程:[初级]C# 中利用 DirectSound 录音
    Mixed mode assembly is built against version 'v1.1.4322' of the runtime and...问题——C# DirectXSound
    DirectX编程:[初级]C#中利用DirectSound播放WAV格式声音[最少只要4句话]
    C#中使用DirectSound录音
    官网下载Google Chrome离线安装包
    设计模式读书笔记[1]:策略模式(Strategy)
  • 原文地址:https://www.cnblogs.com/crazyacking/p/3825753.html
Copyright © 2011-2022 走看看