题目概述
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.
题意
长度为n的数组,一共q次操作,1<=n,q<=10^5
每次操作给出L,R,c,表示区间[L,R]中各个数均加上c
求q次操作结束后,数组中各个元素的值。
输入输出
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
思路分析
题目要求对区间内的数均加上c,基于差分的性质,a数组的区间加等价于差分数组的单点修改。因此我们构造一个差分数组b,b[0]=a[0],b[i]=a[i]-a[i-1],对每次操作,只需b[l-1]+=c,b[r]-=c。
输出操作后的a数组时,利用前缀和的性质,b数组前缀和即为a数组最终数值。
差分的方法使复杂度仅为O(n+q)。
注意
1.对于[1,n]的数组,b[l]+=c,b[r+1]-=c
而我的代码中数组是从0号位置开始存储的,需要修改为b[l-1]+=c,b[r]-=c
2.前面A题被long long坑了这题还是没长记性。q的范围是2e5,c的范围最大是1e5,q*c最大为2e10,而int范围是2e9多,会爆int,因此数组a和b以及计算前缀和的变量sum均开long long型。
代码
#include<iostream>
#include<stdio.h>
using namespace std;
int n,q,c,l,r;
const int maxn=2e5+5;
long long a[maxn],b[maxn];
int main()
{
scanf("%d %d",&n,&q);
for(int i=0;i<n;i++)
scanf("%lld",&a[i]);
b[0]=a[0];
for(int i=1;i<n;i++)
b[i]=a[i]-a[i-1];
for(int i=0;i<q;i++)
{
scanf("%d %d %d",&l,&r,&c);
b[l-1]+=c;//注意是l-1到r,而不是l到r+1
b[r]-=c;
}
long long sum=b[0];
cout<<sum;
for(int i=1;i<n;i++)
{
sum+=b[i];
cout<<" "<<sum;
}
return 0;
}