http://acm.hdu.edu.cn/showproblem.php?pid=4710
Balls rearrangement
Time limit:6000/3000 MS (java/others) Memory limit:32768/32768 K (java/others) total submission (s): 735 Accepted S Ubmission (s): 305
Problem Descriptionbob 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 is numbered from 0 to B-1. After the rearrangement, the ball numbered X should is in the box number b if x = b MoD B. This is very boring, so he wants-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 of he considered would be |a-b|. The total cost was the sum of the cost to move every ball, and it was what Bob was interested in now.
Inputthe first line of the input was an integer T, the number of test cases. (0<T<=50) Then T-test case followed. The only line of all test case is three integers N, A and B. (1<=n<=1000000000, 1<=a,b<=100000).
Outputfor each test case, output the total cost.
Sample Input31000000000 1 18 2 411 5 3
Sample Output0816 Source2013 ACM/ICPC Asia Regional Online--warmup
Analysis:
Simulation, each time you add step, one can put a piece.
AC Code:
1#include <iostream>2#include <stdio.h>3#include <math.h>4 #defineMin (A, b) a>b?b:a5 using namespacestd;6 intMain ()7 {8 intt,n,a,b;9Cin>>T;Ten while(t--) One { ACin>>n>>a>>b; - if(a==b) -printf"0\n"); the Else - { -__int64 ans=0, step=1, I; - for(i=0; i<n;i=i+Step) + { - intstepa=a-i%A; + intstepb=b-i%b; Astep=min (STEPA,STEPB); at__int64 Dis=abs (i%a-i%b); - if(i+step>=N) -Dis=dis* (ni); - Else -dis=dis*Step; -ans=ans+dis; in } -printf"%i64d\n", ans); to } + } - return 0; the}
View Code
Hduoj 4710 Balls rearrangement acm/icpc Asia regional Online--warmup