Balls Rearrangement
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1136 Accepted Submission(s): 474
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.
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<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
规律题目,当时比赛的时候不是自己做的。
赛后补题,一点一点梳理自己的过程,希望有一天自己看的时候会感谢现在的自己。
题意:就是 把编号从0-n的小球对应放进i%a编号的盒子里,然后又买了新盒子,
现在总共有b个盒子,Bob想把球装进i%b编号的盒子里。求重置的最小花费。
每次移动的花费为y - x ,即移动前后盒子编号的差值的绝对值。
算法:
举个例子说明下
在算一个循环节中跳着求和,比如: 20 5 3
红色框(代码中的t)中是是以 %a为0到 %b为0,%b为0到 %a为0。这一段段中的花费是一样的。(这里就减少时间复杂度)。 两个0之间的差值都是固定的
因为数据太大 如果爆搜肯定GG,方法就是找LCM(a,b) 本质进行的都是k*LCM(a,b) (k不一定为整数)
所以就是找到LCM 求出和 (注意下数据范围 long long )
ans=n/LCM(a,b)*add(a,b,k)+add(a,b,n%LCM(a,b)
long long add(long long a,long long b,long long temp)
{
long long ans=0;//区间和
ll x=0;//第一次盒子的第一个数
ll y=0;// 第二个盒子的第一个数
for(ll i=0;i<temp;)//在第一个循环节里面开始计算
{
ll dis=min(a-x,b-y);//求出来最小的距离
if(dis+i>temp)//防止超出范围
dis=temp-i;
ll cha=abs(x-y);//算一下差值
ans=ans+cha*dis; //差值*距离
x=(x+dis)%a;//找到下一个x的位置
y=(y+dis)%b;//同上
i=i+dis;//每次加上dis
}
return ans;
}
int main ()
{
int test;
scanf("%d",&test);
while(test--)
{
long long n,a,b;
scanf("%lld%lld%lld",&n,&a,&b);
long long temp=lcm(a,b);//a b的最小公倍数
if(a==b)
printf("0\n");
else
{
long long sum=n/temp*add(a,b,temp)+add(a,b,n%temp);//循环节+最后一次
printf("%lld\n",sum);
}
}
return 0;
}
如果谁有超出数据的范围,麻烦评论下 ,谢谢。