Appoint description:
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.
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).
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
挺好的数学题,不过感觉题意给的好像有点奇怪,明明是a=x mod A么,看了好久,这题对于小白的我来说就是直接暴力,但那明显会超时,看了别人的代码,其实感觉就是在原有基础上细加优化,这一点是最近需要锻炼并有初步掌握的,同时这个题有个问题就是关于答案必须是—int64,而且要与之计算的全部都是这种类型,混合类型会WA,很好奇不知道为什么,而且long long也不行,还是不知道为什么,先留着等以后问吧。
#include<stdio.h>
#include<stdlib.h>
#define min(a,b)(a<b?a:b)
__int64 GCD(__int64 a,__int64 b){
__int64 temp;
while(b){
temp=a%b;
a=b;
b=temp;
}
return a;
}
__int64 LCM(__int64 a,__int64 b){
return a*b/GCD(a,b);
}
__int64 abs(__int64 num){//好像include<math.h>里面的abs不支持64位得自己写
return num>0?num:-num;
}
__int64 find(__int64 len,__int64 a,__int64 b){//跟别人学写的这段,感觉写的挺好
__int64 sum=0,i=0,j=0,temp=0,size=0;
while(size<len){
temp=min(len-size,min(a-i,b-j));//求共有的上升区间
sum+=abs(i-j)*temp;//同一段上升区间差值相同,这样的话就节省很多时间
i=(i+temp)%a;
j=(j+temp)%b;
size+=temp;
}
return sum;
}
int main(){
int t;
__int64 n,ans,size,a,b;//据别人说好像必须得全部写成64位要不然混算会出错
scanf("%d",&t);
while(t--){
scanf("%I64d %I64d %I64d",&n,&a,&b);
size=LCM(a,b);
if(size>=n)ans=find(n,a,b);
else{
ans=find(size,a,b)*(n/size)+find(n%size,a,b);//这里是根据相同升序差值相同节省时间要不然会超
}
printf("%I64d\n",ans);
}
return 0;
}