Balls Rearrangement
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 1682 Accepted Submission(s): 634
Problem 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
Source
这个题我做的有点复杂,可是跑得很快,0MS
我的每次移动a
#include <stdio.h>
__int64 fabs(__int64 a)
{
if(a<0)return -a;
return a;
}
__int64 gcd(__int64 a,__int64 b)
{
if(a==0)return b;
return gcd(b%a,a);
}
int main ()
{
__int64 tcase,n,a,b,i,k1,k2,temp,j,k;
__int64 tempsum,mm,sum;
int m1;
scanf("%I64d",&tcase);
while(tcase--)
{
scanf("%I64d%I64d%I64d",&n,&a,&b);
if(a==b)
{
printf("0\n");
continue;
}
if(a>b)
{
temp=a;a=b;b=temp;
}
mm=a*b/gcd(a,b);
m1=n/mm;
sum=0;
if(m1!=0)
for(i=a-1,j=-1;i<mm;i=i+a)//算出一个周期内的,j记录的是b中当前的下标
{
if(j+a<b)
{
sum+=(j+1)*a;
j=j+a;
}
else
{
sum+=(j+1)*(b-j-1)+(b-j-1)*(a-b+j+1);
j=j+a-b;
}
}
//printf("%I64d\n",sum);
sum=sum*m1;
//printf("%I64d\n",sum);
k=n%mm;
for(i=a-1,j=-1;i<k;i=i+a)//这些就是下标计算了,小心点
{
if(j+a<b)
{
sum+=(j+1)*a;
j=j+a;
}
else
{
sum+=(j+1)*(b-j-1)+(b-j-1)*(a-b+j+1);
j=j+a-b;
}
}
//printf("%d %I64d\n",i,sum);
if(n%a!=0)//这是算最后无法整除这一部分了,这里借用了网上用的比较多的那种方法来计算的
{
i=n-n%a;
k1=0;
k2=(j+1)%b;
if(b-k2<n-i)//最后一段b下标有为0的情况
sum+=k2*(b-k2)+(n+k2-i-b)*(k1+b-k2);
else sum+=k2*(n-i);
/*for(i=n-n%a,k1=0,k2=j+1;i<n;i++,k1++,k2++)//最开始用的死算法,15ms
{
if(k1>=a)
k1=0;
if(k2>=b)
k2=0;
sum+=fabs(k1-k2);
//printf("%d %I64d\n",i,sum);
}*/
}
printf("%I64d\n",sum);
}
return 0;
}