快速切题sgu126. 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

思路 1 只记录两个箱子的差值X,那么X=0的时候就能1次成功了
2 X的转移是X=SUM-2*X或者X=2*X-SUM(也即绝对值,X>0),注意到每次分母扩2倍,也就是说不超过32次
之后随便写一写就好啦,这个纯属胡整,我要睡觉!
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
int a,b,sum;
queue<int >que;
set <int >st;
int main(){
    scanf("%d%d",&a,&b);
    if(a>b)swap(a,b);
    if(a==0||b==0)puts("0");
    else if(a==b)puts("1");
    else if((b-a)*2==a+b)puts("2");
    else if((b+a)&1)puts("-1");
    else {
        int sub=b-a;
        sum=a+b;
        st.insert(sub);
        que.push(sub);
        int step=0;
        while(!que.empty()){
            sub=que.front();que.pop();step++;
            if(sub==0||step>64)break;
            int t=abs(sum-2*sub);
            if(st.count(t)==0){que.push(t);st.insert(t);}
        }
        if(sub==0)printf("%d\n",step);
        else puts("-1");
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/xuesu/p/4008886.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值