找规律:Ball rearange

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

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stdlib.h>
using namespace std;
long long gcd(int a,int b)
{
    return a%b==0?b:gcd(b,a%b);
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
       long long p,a,b;
        scanf("%I64d%I64d%I64d",&p,&a,&b);
        if(a==b)
        {
            printf("0\n");
            continue;
        }
        long long lcm=a/gcd(a,b)*b;
        long long con=min(p,lcm);
        long long x=p/con,y=p%con;
        long long cnt=0,sum=0,i=0,j=0;
        while(cnt<con)
        {
            i%=a,j%=b;
            int temp=min(a-i,b-j);
            if(temp>con-cnt)//注意不可以超过步数
                temp=con-cnt;
            sum+=abs(i-j)*temp;
            i+=temp;
            j+=temp;
            cnt+=temp;
        }
        sum=sum*x;
        cnt=j=i=0;
        while(cnt<y)
        {
            i%=a,j%=b;
            int temp=min(a-i,b-j);
            if(temp>y-cnt)
                temp=y-cnt;
            sum+=abs(i-j)*temp;
            i+=temp;
            j+=temp;
             cnt+=temp;
        }
        printf("%I64d\n",sum);
    }
    return 0;
}

1,要用long long ;
2,找寻环节,将循环节之内和之外的分开处理;
3,再循环节之内的,也不用一个一个的加,可以将相同结果的一起加上,否则会超时;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值