题目相关
题目链接
AtCoder Beginner Contest 181 B 题,https://atcoder.jp/contests/abc181/tasks/abc181_b。
Problem Statement
We have a blackboard with nothing written on it. Takahashi will do N operations to write integers on it.
In the i-th operation, he will write each integer from Ai through Bi once, for a total of Bi−Ai+1 integers.
Find the sum of the integers written on the blackboard after the N operations.
Input
Input is given from Standard Input in the following format:
N
A1 B1
.
.
.
AN BN
Output
Print the sum of the integers written on the blackboard after the N operations.
Samples1
Sample Input 1
2
1 3
3 5
Sample Output 1
18
Explaination
In the 1-st operation, he will write 1, 2, and 3 on the blackboard.
In the 2-nd operation, he will write 3, 4, and 5 on the blackboard.
The sum of the integers written is 1+2+3+3+4+5=18.
Samples2
Sample Input 2
3
11 13
17 47
359 44683
Sample Output 2
998244353
Samples3
Sample Input 3
1
1 1000000
Sample Output 3
500000500000
Constraints
- All values in input are integers.
- 1≤N≤10^5
- 1≤Ai≤Bi≤10^6
题解报告
题目翻译
高桥在白板写出 N 行,每行包括两个整数。第 i 行操作,将写出数据 Ai 和 Bi,这样一共有 Bi-Ai+1 个数字。请计算出这 N 次操作包含的所有数据总和。
题目分析
回到了 AtCoder Beginner Contest 后,感觉明显好多了。看来自己的水平也就是这样。
我们可以知道每次高桥写出一个公差为 1,数量为 Bi-Ai+1 个数字。我们可以根据等差数量求和公式: 来计算。
数据规模估计
从数据限制可知,最终的总和最大值为:。说明需要使用 long long 来表示。
AC 参考代码
//https://atcoder.jp/contests/abc181/tasks/abc181_b
//B - Trapezoid Sum
//d=1的等差数列求和
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
long long ans=0;
while (n--) {
long long a,b;
cin>>a>>b;
long long tot=b-a+1;
ans+=(a*tot+tot*(tot-1)/2);
}
cout<<ans<<"\n";
return 0;
}
时间复杂度
O(N)。