hdu4710 Balls Rearrangement(数学公式+取模)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kirito_Acmer/article/details/51418326

Balls Rearrangement

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 945    Accepted Submission(s): 380


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

题意:有n个球,编号为0~n-1,有a个盒子,编号为0~a-1,每一个球放在第x%a(0<=x<=n-1)个盒子里,现在有b个盒子,每一个球要重新放到x%b个盒子内,如果编号相同则不用移动,如果编号不同,那么每一次移动的价值为abs(x%a-x%b),问总价值是多少。

思路:首先容易发现,循环节最大为lcm(a,b),即答案是n/p*jisuan(a,b,p)+jisuan(a,b,n%p),但是我们会发现,如果a,b是接近100000的两个素数,那么我们光是从0~lcm(a,b)做一遍会超时,所以要用别的方法。模拟几个样例后会发现,从x%a=0或者x%b=0到下一个x%a=0或者x%b=0这一段区间内,所有数从a盒子搬到b盒子产生的价值是一样的,所以我们可以"跳着"暴力,然后就不会超时了。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<bitset>
#include<algorithm>
using namespace std;
#define lson th<<1
#define rson th<<1|1
typedef long long ll;
typedef long double ldb;
#define inf 99999999
#define pi acos(-1.0)

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

ll lcm(int a,int b){
    return (ll)a*(ll)b/gcd(a,b);
}
ll jisuan(ll a,ll b,ll p)
{
    
    ll t,x=0,y=0,c=0;
    ll ans=0;
    while(c<p)
    {
        t=min(a-x,b-y);
        if(c+t>=p){
            t=p-c;
        }
        ans+=(ll)t*abs(x-y);
        c+=t;
        x=(x+t)%a;
        y=(y+t)%b;
    }
    return ans;
}

int main()
{
    int m,i,j,T;
    ll n,a,b;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld%lld",&n,&a,&b);
        ll p=lcm(a,b);
        printf("%lld\n",(ll)n/p*(ll)jisuan(a,b,p)+jisuan(a,b,n%p) );
    }
    return 0;
}


没有更多推荐了,返回首页