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,再循环节之内的,也不用一个一个的加,可以将相同结果的一起加上,否则会超时;