题目
One day, the magic cat decided to investigate TT’s ability by giving a problem to him. That is select n cities from the world map, and a[i] represents the asset value owned by the i-th city.
Then the magic cat will perform several operations. Each turn is to choose the city in the interval [l,r] and increase their asset value by c. And finally, it is required to give the asset value of each city after q operations.
Input
The first line contains two integers n,q(1≤n,q≤2⋅105) — the number of cities and operations.
The second line contains elements of the sequence a: integer numbers a1,a2,…,an (−106≤ai≤106).
Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−105≤c≤105) for the i-th operation.
Output
Print n integers a1,a2,…,an one per line, and ai should be equal to the final asset value of the i-th city.
Sample Input
4 2
-3 6 8 4
4 4 -2
3 3 1
Sample Output
-3 6 9 2
思路
题意看起来很简单,但是如果直接对区间中的点逐个进行修改的话,复杂度为O(qn),超时。
由于是对一段区间内的所有点都进行操作,故可以采用前缀和与差分,将原数组转化为差分数组,将区间修改变为点修改。
新数组b[i]=a[i]-a[i-1] (i>=1),则b[]记录的是a[]中相邻两项的差值。又a[1]也可能修改,故将a[0]赋为0作为将b[]恢复为a[]的基点,保持不变。
则当修改区间[l,r]之间的点的值时,只需修改b[l],b[r+1],即a[l]与a[l-1]的差值以及a[r+1]与a[r]的差值。
b[]转为a[]时,a[i]=a[i-1]+b[i]。
代码
#include <cstdio>
#include <algorithm>
using namespace std;
long long a[200005],b[200005];//范围q*n最大为2*10^10
int main() {
int n,q;
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)//从1开始,留出a[0]=0,a[1]要与a[0]查分,要有一个固定的开始值
scanf("%lld",&a[i]);
for(int i=1;i<=n;i++)
b[i]=a[i]-a[i-1];
for(int i=0;i<q;i++){
int l,r,c;
scanf("%d%d%d",&l,&r,&c);
b[l]+=c;
b[r+1]-=c;
}
for(int i=1;i<=n;i++)
a[i]=a[i-1]+b[i];
for(int i=1;i<=n;i++)
printf("%lld ",a[i]);
}
总结
注意数据范围,应使用long long,以后需要大致计算一下得到的数据范围,使用合适的类型。
题目链接