您的位置:首页 > 其它

codeforces 476c Dreamoon and Sums

2015-08-10 22:09 489 查看
题解: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;
//		}

	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: