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 6

a b

先從b移2個給a,

a就有4個了,

a和b都有4個了,

再把a的4個移到b,

a就全部到b了,

這樣就操作了倆步。。


分析

我們用(x, y)表示兩個盒子裏分別有x個球和y個球(不區分是哪個盒子)。假設總共有n個球,經過k步把所有球移到一個盒子裏。如果反過來推的話,那麼各盒子中球的個數爲:

第k步:   (0, n);

第k-1步:(n/2, n/2);

第k-2步:(n/4, 3n/4);

第k-3步:(n/8, 7n/8)或(3n/8, 5n/8);

第k-4步:(n/16, 15n/16)或(3n/16, 13n/16)或(5n/16, 11n/16)或(7n/16, 9n/16);

......


這樣,我們就發現了規律:除(0, n)這種情況外(一步即可),若(A, B)能化成(x*c, y*c)這種形式,(c爲A、B的最大公約數,x和y均爲奇數且x+y=2^k,k=1,2,...)則k即爲所求的最小步數,輸出k;否則,輸出-1。

2k=(x+y)/gcd(a,b),k即爲答案

代碼:

#include<iostream>
#include<cstdio>
using namespace std;
int a,b,t,gg,i;
int main()
{
    int m,k;
    while(~scanf("%d %d",&a,&b))
    {
       if(a>b)
        swap(a,b);
        t=b%a;
        while(t!=0)
        {
            b=a;
            a=t;
            t=b%a;
        }
        gg=a;
        a-=gg;
        b-=gg;
        m=a+b;
        k=0;
        while(m>1)
        {
            if(m%2==0)
            {
                k++;
                m=m/2;
            }
            else
            {
                k=-1;
                break;
            }
        }
        printf("%d\n",k);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章