整理的算法模板:ACM算法模板总结(分类详细版)
D - Sum of Large Numbers /
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 400400 points
Problem Statement
We have N+1N+1 integers: 1010010100, 10100+110100+1, ..., 10100+N10100+N.
We will choose KK or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (109+7)(109+7).
Constraints
- 1≤N≤2×1051≤N≤2×105
- 1≤K≤N+11≤K≤N+1
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
NN KK
Output
Print the number of possible values of the sum, modulo (109+7)(109+7).
Sample Input 1 Copy
Copy
3 2
Sample Output 1 Copy
Copy
10
The sum can take 1010 values, as follows:
- (10100)+(10100+1)=2×10100+1(10100)+(10100+1)=2×10100+1
- (10100)+(10100+2)=2×10100+2(10100)+(10100+2)=2×10100+2
- (10100)+(10100+3)=(10100+1)+(10100+2)=2×10100+3(10100)+(10100+3)=(10100+1)+(10100+2)=2×10100+3
- (10100+1)+(10100+3)=2×10100+4(10100+1)+(10100+3)=2×10100+4
- (10100+2)+(10100+3)=2×10100+5(10100+2)+(10100+3)=2×10100+5
- (10100)+(10100+1)+(10100+2)=3×10100+3(10100)+(10100+1)+(10100+2)=3×10100+3
- (10100)+(10100+1)+(10100+3)=3×10100+4(10100)+(10100+1)+(10100+3)=3×10100+4
- (10100)+(10100+2)+(10100+3)=3×10100+5(10100)+(10100+2)+(10100+3)=3×10100+5
- (10100+1)+(10100+2)+(10100+3)=3×10100+6(10100+1)+(10100+2)+(10100+3)=3×10100+6
- (10100)+(10100+1)+(10100+2)+(10100+3)=4×10100+6(10100)+(10100+1)+(10100+2)+(10100+3)=4×10100+6
Sample Input 2 Copy
Copy
200000 200001
Sample Output 2 Copy
Copy
1
We must choose all of the integers, so the sum can take just 11 value.
Sample Input 3 Copy
Copy
141421 35623
Sample Output 3 Copy
Copy
220280457
规律如下:
样例来说,把10的100次方看成0,那么就变成 0 1 2 3 ;
区间长度为2的区间和的范围是:0+1=1, 2+3=5;也就是1~5;
区间长度为3的区间和的范围是: 0+1+2=3, 1+2+3=6; 也就是3~6;
区间长度为4的区间和的范围是: 6 ~ 6 ;
所有范围内的数加起来就是10个;
所以对于每一个区间长度,都求出来范围的下界和上界即可;注意中间求和的过程中要用上界减去下界,此时要先减再mod;
说下我自己容易出错的地方(大佬自动跳过):当题目要求结果mod上一个数时,通常计算过程中要处处取模,否则会有隐患,但是如果计算中间出现了两个大数相减,比如算出来两个大数 a b(a<b);如果用b%mod-a%mod,数据大一点就gg了;正确的应该先减后mod;(b-a+mod)%mod;
#include <bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
typedef long long ll;
int main()
{
ll n,k;
cin >>n>>k;
ll ans=0;
while(k<=n)
{
ll res=(k*(n-k+1+n)/2-k*(k-1)/2+1+mod)%mod;
ans=(ans+res)%mod;
k++;
}
ans++;
cout <<ans%mod<<endl;
}