HDU 4710 && HDU 4611 Balls Rearrangement (热身赛第五题)

转载请注明出处:http://blog.csdn.net/a1dark

分析:这题以前做过、看着就很熟悉、原来是原题、其实就是找规律、

#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <iostream>  
#include <cmath>  
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/gcd(a,b)*b;  
}  
long long cost(long long n,long long a,long long b)  {  
    long long ans=0,x=0,y=0,tmp=0,now=0;  
    while(now<n)  
    {  
        tmp=min(a-x,b-y);
        if(tmp+now>n)  
            tmp=n-now;  
        ans+=tmp*(abs(x-y));  
        x=(x+tmp)%a;  
        y=(y+tmp)%b;  
        now+=tmp;  
    }  
    return ans;  
}  
int main()  {  
    int t;  
    cin>>t;  
    long long n,a,b;  
    while(t--)  {  
        cin>>n>>a>>b;  
        long long l=lcm(a,b);  
        if(l<=n)  
            cout<<cost(l,a,b)*(n/l)+cost(n%l,a,b)<<endl;  
        else  
            cout<<cost(n,a,b)<<endl;  
    }  
    return 0;  
}  


你可能感兴趣的:(数学,ACM)