hdu4611Balls Rearrangement

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

题意:给定多组数据,每组有n,a,b。求sigma(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的价值啦,剩下的那一点n%lcm一样处理就行啦。O(t*a*b/gcd(a,b)/gcd(a,b))。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=200010;
const int MAX=1000000100;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=1000000007;
const int INF=1000000010;
const double pi=acos(-1.0);
typedef double db;
typedef unsigned long long ull;
ll k,f[N];
ll gcd(ll a,ll b) {
    return b==0 ? a:gcd(b,a%b);
}
ll get(ll a,ll b) {
    ll x=a,y=b,ret=0;
    f[++k]=0;
    while (x!=y)
    if (x<y) { f[++k]=x;x+=a; }
    else { f[++k]=y;y+=b; }
    f[++k]=x;
    for (int i=1;i<k;i++) ret+=(ll)(f[i+1]-f[i])*abs(f[i]%a-f[i]%b);
    return ret;
}
int main()
{
    int i,t;
    ll a,b,g,n,lcm,ans;
    scanf("%d", &t);
    while (t--) {
        scanf("%I64d%I64d%I64d", &n, &a, &b);
        lcm=a/gcd(a,b)*b;k=0;
        ans=n/lcm*get(a,b);
        if (n%lcm!=0) {
            n%=lcm;
            while (f[k]>n) k--;
            f[++k]=n;
            for (i=1;i<k;i++) ans+=(ll)(f[i+1]-f[i])*abs(f[i]%a-f[i]%b);
        }
        printf("%I64d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值