题意:
Thanks to everyone’s help last week, TT finally got a cute cat. But what TT didn’t expect is that this is a magic cat.
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.
Could you help TT find the answer?
输入输出要求:
The first line contains two integers n,q (1≤n,q≤2⋅10^5)— the number of cities and operations.
The second line contains elements of the sequence a: integer numbers a1,a2,…,an (−10^6≤ai≤10 ^6).
Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−10^5≤c≤10 ^5) for the i-th operation.
Print nn integers a1,a2,…,an one per line, and aishould be equal to the final asset value of the i-th city.
样例输入1:
4 2
-3 6 8 4
4 4 -2
3 3 1
样例输出1:
-3 6 9 2
样例输入2:
2 1
5 -2
1 2 4
样例输出2:
9 2
样例输入3:
1 2
0
1 1 -8
1 1 -6
样例输出3:
-14
思路:
暴力做法:
直接循环,将[l,r]中的每个数依次+c,进行q次操作,复杂度为O(qn),超时
差分:
本题明显是对一个区间的数据进行操作,利用差分的特点,将A数组区间的操作改为对B数组的单点操作
差分构造方式
原数组 A,差分数组 B, 数组范围 [1, n]
• B[1] = A[1]
• B[i] = A[i] - A[i-1]
差分特点
• B 数组前缀和⇔A 数组元素值
SUM{B[1~i]} = A[i]
• A 数组的区间加⇔B 数组的单点修改
A[L]~A[R] 均加上 c 等价于 B[L] += c, B[R+1] -= c
解题:
由上面的分析,将the asset value owned by the i-th city构造成A数组,并获得其差分数组,将A的区间变化转化为B的端点变化
总结:
1.能够根据“区间变化->端点变化“判断出使用差分数组
2.差分数组求sum,保险起见使用long long型数据
代码:
#include<iostream>
using namespace std;
int n,q,l,r,c;
long long a[200010],b[200010],b_sum[200010];
int main(){
cin>>n>>q;
for(int i=1;i<=n;i++){
cin>>a[i];
if(i==1) b[i]=a[i];
else b[i]=a[i]-a[i-1];
}
for(int i=0;i<q;i++){
cin>>l>>r>>c;
b[l]+=c;
b[r+1]-=c;
}
for(int i=1;i<=n;i++){
b_sum[i]=b_sum[i-1]+b[i];
if(i!=n) cout<<b_sum[i]<<" ";
else cout<<b_sum[i]<<endl;
}
return 0;
}