hdu 4611Balls Rearrangement

Balls Rearrangement

  Bob has N balls and A boxes. He numbers the balls from 0 to N-1, and numbers the boxes from 0 to A-1. To find the balls easily, he puts the ball numbered x into the box numbered a if x = a mod A.   Some day Bob buys B new boxes, and he wants to rearrange the balls from the old boxes to the new boxes. The new boxes are numbered from 0 to B-1. After the rearrangement, the ball numbered x should be in the box number b if x = b mod B.
  This work may be very boring, so he wants to know the cost before the rearrangement. If he moves a ball from the old box numbered a to the new box numbered b, the cost he considered would be |a-b|. The total cost is the sum of the cost to move every ball, and it is what Bob is interested in now.  

Input
  The first line of the input is an integer T, the number of test cases.(0<T<=50) 
  Then T test case followed. The only line of each test case are three integers N, A and B.(1<=N<=1000000000, 1<=A,B<=100000).
 
Output
  For each test case, output the total cost.
 
Sample Input
    
    
3 1000000000 1 1 8 2 4 11 5 3
 
Sample Output
    
    
0 8 16
题意:求 i=0~N-1  abs(i%A-i%B) 的和
题解:读懂这个题目 直接暴力必然超时..
        考虑分块处理 求lcm(A,B)循环节,因为a=10^5,爆了求lcm的贡献不好求,我们想想该怎么快速求得一个lcm块中的价值。如果你随便打个表或者画画图就会发现很多连续的段内是相同的值,那么仔细观察下这些段的分界线是什么呢?是A的倍数或者B的倍数。显然在一个lcm内会有b/gcd个a的倍数,b同理。那么我们会发现一个lcm最多被分为a+b个段,然后for一遍就能统计出一个lcm的价值,对于不足lcm的部分,拿出来单独处理,尽量分段求价值,分段不足时,直接暴力。
long long  gcd(long long a,long long b)
{
    return b==0?a:gcd(b,a%b);
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        long long n,a,b;
        scanf("%lld%lld%lld",&n,&a,&b);
        long long ans = 0;
        long long e = a/gcd(a,b)*b;
        long long ti = n/e;
        long long ty = n%e;
        long long now=0;
        long long tmp;
        long long x=0,y=0;
        while(now<e)
        {
            tmp=min(a-x,b-y);
            if (now+tmp>e)
                tmp=e-now;
            ans+=tmp*abs(x-y);
            x=(x+tmp)%a;
            y=(y+tmp)%b;
            now+=tmp;
        }
        ans*=ti;
        now = 0;
        x = 0;
        y = 0;
        while(now<ty)
        {
            tmp=min(a-x,b-y);
            if (now+tmp>ty)
                tmp=ty-now;
            ans+=tmp*abs(x-y);
            x=(x+tmp)%a;
            y=(y+tmp)%b;
            now+=tmp;
        }
        cout<<ans<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值