HDU 4611 Balls Rearrangement 数学

Balls Rearrangement

题目连接:

http://acm.hdu.edu.cn/showproblem.php?pid=4611

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

Hint

题意

有n个数,给你a和b

T1[i]=i%a,T2[i]=i%b

求sigma(T1[i]-T2[i])

题解:

简单思考一下,他们之间的差一开始都是0的,当遇到某个数是a的倍数的时候,他们之间每个数的差就会增加a,遇到某个数是b的倍数的时候,差就会减少b

根据这个去跑一个lcm周期的答案就好了

然后再暴力算最后一个n%lcm的答案就好了

代码

#include<bits/stdc++.h>
using namespace std;

long long gcd(long long a,long long b)
{
    if(b==0)return a;
    return gcd(b,a%b);
}
long long lcm(long long a,long long b)
{
    return a*b/gcd(a,b);
}
vector<long long>p;
void init()
{
    p.clear();
}
void solve()
{
    init();
    long long n,a,b;
    cin>>n>>a>>b;
    long long c = lcm(a,b);
    for(long long i=1;i*a<=c;p.push_back(i*a),i++);
    for(long long i=1;i*b<=c;p.push_back(i*b),i++);
    p.push_back(0);sort(p.begin(),p.end());p.erase(unique(p.begin(),p.end()),p.end());
    long long ans = 0,now = 0;
    for(int i=1;i<p.size()-1;i++)
    {
        if(p[i]%a==0)now-=a;
        if(p[i]%b==0)now+=b;
        ans+=abs(now)*(p[i+1]-p[i]);
    }
    long long k = n/c;
    long long Ans = 0;
    Ans = Ans + k*ans;
    k = n%c;
    int kkk = 0;
    for(int i=0;i<p.size()-1&&p[i+1]<k;i++)
    {
        kkk = i+1;
        if(p[i]%a==0)now-=a;
        if(p[i]%b==0)now+=b;
        Ans+=abs(now)*(p[i+1]-p[i]);
    }
    if(p[kkk]%a==0)now-=a;
    if(p[kkk]%b==0)now+=b;
    Ans+=abs(now)*(k-p[kkk]);
    cout<<Ans<<endl;
}
int main()
{
    int t;scanf("%d",&t);
    while(t--)solve();
    return 0;
}

转载于:https://www.cnblogs.com/qscqesze/p/5373566.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值