题解:http://codeforces.com/blog/entry/14256
If we fix the value of k, and let d = div(x, b), m = mod(x, b), we have :
d = mk
x = db + m
So we have x = mkb + m = (kb + 1) * m.
And we know m would be in range [1, b - 1] because it's a remainder and x is positive, so the sum of x of that fixed k would be
.
Next we should notice that if an integer x is nice it can only be nice for a single particular k because a given x uniquely defines div(x, b) and mod(x, b).
Thus the final answer would be sum up for all individual k:
which can be calculated in O(a) and will pass the time limit of 1.5 seconds.
Also the formula above can be expanded to
. Dreamoon says he's too lazy to do this part, so if you use O(1) solution you just computed the answer faster than Dreamoon!!!
Note that no matter which approach one should be very careful of overflowing of the integer data type of the used language. For example one should do a module after every multiplication if using 64-bit integer type. And pay attention to precedence of operations: take c++ for example a+b%c would be executed as a+(b%c) instead of (a+b)%c, another c++ example a*(b*c)%m would be executed as (a*(b*c))%m instead of a*((b*c)%m).
Thanks saurabhsuniljain for pointing out the preceding problem and examples in the comment!
time complexity: O(1)
sample code: 8215188
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int M=1e9+7;
const int L=500000004;
int main()
{
long long a,b;
long long s=0;
while(scanf("%I64d%I64d",&a,&b)!=EOF)
{
s=0;
printf("%I64d\n",(((a*(a+1)%M*L%M*b%M+a))*((b*(b-1)%M*L)%M)%M));
// for(int i=1;i<=a;i++)
// {
// s=(s+(i*b+1)%M*((b*(b-1)/2)%M))%M;
// }
}
}
本文解析了Codeforces上一篇关于特定数学问题的算法解答,通过固定变量k,利用除法和取余运算推导出x与m的关系,并给出了解决方案的时间复杂度为O(1)。此外还提供了避免整数溢出的方法及示例代码。
380

被折叠的 条评论
为什么被折叠?



