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.
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).
3 1000000000 1 1 8 2 4 11 5 3
0
8
16
题目说的很简单,就是放球的问题,归为数学问题就是让你求一下abs(i%a-i%a),当i<x是的所有的和,思想很容易想到a,b的最小公倍数为一个循环节,但当这两个数都很大的时候他们的最小公倍数也是很大的,所以需要考虑一下再继续优化,这是在纸上写一写数。你就会发现这些数有一些规律,在一些相邻的区间上差值是一样的,这时就考虑可不可以一个区间一个区间的去求值呢,但是自己还是很菜在打比赛的时候没能写出来的,鬼节原因还是自己比较狭隘,不够大气,还是不能从整体上上看待一个问题,只是一点点拼凑,但是做的题多了就会发现这种思想是不可取的,做题一定要从总体上把握题目,。。。。
赛后看了题解,发现博主只用了区区几行代码就把我比赛时没敲出来的代码写出来,很是钦佩,但一看代码就只有一个感觉,还是自己太菜!其实做法很简单,但是脑子里的思路一定要清晰
ac代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
long long gcd(long long a,long long b)
{
return b?gcd(b,a%b):a;
}
long long lcm(long long a,long long b)
{
return a/gcd(a,b)*b;
}
long long right(long long a,long long b,long long x)
{
long long tmp,i,s;
i=0;s=0;
while(i<x)
{
tmp=min(a-i%a,b-i%b);
if(tmp+i >= x)
tmp=x-i;
s+=abs(i%a-i%b)*tmp;
i+=tmp;
}
return s;
}
int main()
{
long long x,a,b,sum,h;
cin>>h;
while(h--)
{
cin>>x>>a>>b;
if(a>b)
{
long long t=a;
a=b;
b=t;
}
sum=0;
long long y=lcm(a,b);
if(x<y)
sum=right(a,b,x);
else
sum=x/y*right(a,b,y)+right(a,b,x%y);
cout<<sum<<endl;
}
return 0;
}