HDU 4611--Balls Rearrangement--数论找出循环节+跳跃求值

Balls Rearrangement

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1984    Accepted Submission(s): 732


Problem Description
  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
 

Source
 

Recommend
zhuyuanchen520


多校第二场的题目,最近打了热身赛,居然又遇到了= =#。。。

又做了一遍,发现人老了记忆力果真衰退,很多东西都忘了。。。

首先题意很容易理解,就是将N个球放到A个盒子,再放到B个盒子中转移产生的差值。

可以发现,|a-b|=|x%A-x%B|,

而x是一个大于0小于N的数,

可以题目可以看成三条轴,

第一条轴是以A为循环节的无限下去的轴线,

第二条轴是以B为循环节的无限下去的轴线,

第三条轴是从0开始不断加1直到为N-1的轴线,

由于计算的是ans=|x%A-x%B|的值,可以发现,倘若第一和第二条轴线的循环节有共同段,

那么在这共同段长度中,ans的值不会变。

即第三条轴线在当前结点的大小run到min(a-flag%a,b-flag%b)中,ans的值不会变。

右可以发现,lcm(a,b)中产生的总的ans的值为一个循环节。

注意Long long以及N>run的边界,以下是代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;

int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}

ll lcm(int a,int b)
{
    return (ll)a/gcd(a,b)*(ll)b;
}

ll cal(ll n,int a,int b)
{
    ll ans=0;
    ll run=0;
    while(run<n)
    {
        ans+=abs(run%a-run%b)*min(n-run,min(a-run%a,b-run%b));
        run+=min(n-run,min(a-run%a,b-run%b));
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,a,b;
        ll ans;
        scanf("%d%d%d",&n,&a,&b);
        ll lc=lcm(a,b);
        if(lc>=n)
            ans=cal(n,a,b);
        else
            ans=cal(n%lc,a,b)+cal(lc,a,b)*(n/lc);
        cout<<ans<<endl;
        //printf("%I64d\n",ans);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值