Balls Rearrangement
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 388 Accepted Submission(s): 142
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.
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).
Output
For each test case, output the total cost.
Sample Input
3
1000000000 1 1
8 2 4
11 5 3
Sample Output
Source
2013 Multi-University Training Contest 2
Recommend
zhuyuanchen520
额,水题,连续相同的数字一起算就可以了,连续相同的部分截止就两种情况,第一种是第一个数要回0了,第二种是第二个数要回0了。另外,还需要分两种情况讨论,如果lcm比较小就直接爆循环节,lcm较大就直接算……
目测我年事已高了,少了一个括号调试了好久好久……尼玛……
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
long long gcd(long long x,long long y)
{
return y==0?x:gcd(y,x%y);
}
long long Count(long long n,long long a,long long b)
{
// printf("%lld %lld %lld\n",n,a,b);
long long now=0,ret=0,tmp,x=0,y=0;
while(now<n)
{
tmp=min(a-x,b-y);
if (now+tmp>n) tmp=n-now;
ret+=tmp*abs(x-y);
x=(x+tmp)%a;
y=(y+tmp)%b;
now+=tmp;
// printf("%lld %lld %lld %lld\n",now,x,y,ret);
}
return ret;
}
int main()
{
int i,j,T;
long long a,b,n,l,ans;
scanf("%d",&T);
while(T--)
{
cin>>n>>a>>b;
l=a*b/gcd(a,b);
if (l>=n) ans=Count(n,a,b);
else ans=Count(l,a,b)*(n/l)+Count(n%l,a,b);
cout<<ans<<endl;
}
return 0;
}