Balls Rearrangement
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 1213 Accepted Submission(s): 471
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
Recommend
zhuyuanchen520
题意:有3个数字 N, a, b; 求 abs(n % a - n % b) 的和 n是从0~ N - 1
思路: 模拟
样例 11 5 3
不能一个个的算, 要跳着算。 同是递增的差值一样。
是对称的。 有点想算 (1 + 2 + 3 + …… + k) * 2 >= n; 即 (1 + k) * k >= n; k = sqrt(n);
复杂度粗略算得为 O(sqrt(n)); 不会超时。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int V = 200000 + 5;
const int MaxN = 100000 + 5;
const int mod = 1000000000 + 7;
int T;
__int64 n, a, b;
__int64 LCM(__int64 a, __int64 b) {
__int64 aa = max(a, b);
__int64 bb = min(a, b);
do {
__int64 r = aa % bb;
aa = bb;
bb = r;
}while(bb);
return a * b / aa;
}
__int64 f(__int64 n, __int64 a, __int64 b) {
__int64 a_mod, b_mod, start, ans;
ans = start = a_mod = b_mod = 0;
while(start < n) {
__int64 len = min(a - a_mod, b - b_mod);
if(len > n - start)
len = n - start;
ans += len * abs(b_mod - a_mod);
a_mod = (a_mod + len) % a;
b_mod = (b_mod + len) % b;
start += len;
}
return ans;
}
int main() {
scanf("%d", &T);
while(T--) {
__int64 ans = 0;
scanf("%I64d%I64d%I64d", &n, &a, &b);
__int64 lcm = LCM(a, b);
if(lcm >= n) //如果最小公倍数超过 n 直接算n次;
ans = f(n, a, b);
else //否则算公倍数以内的 * 倍数 再加上多出的
ans = f(lcm, a, b) * (n / lcm) + f(n % lcm, a, b);
printf("%I64d\n", ans);
}
}