B-TT‘s Magic Cat (差分数组)
一、题目描述
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?
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.
Examples
Input
4 2
-3 6 8 4
4 4 -2
3 3 1
Output
-3 6 9 2
Input
2 1
5 -2
1 2 4
Output
9 2
Input
1 2
0
1 1 -8
1 1 -6
Output
-14
二、思路与算法
本题核心为差分数组b[i]的实现和使用。
b[0]=a[0];
b[i]=a[i]-a[i-1]; //(i>0)
根据定义可以看到,i不为0时,a[i]=差分数组b[i]前i项和。
而想对a数组区间[l,r]每个元素都做+c操作时,差分数组只需要给b[l]加c,再给b[r+1]减c。
所以,本题只需要每次操作中对对应b[i]操作,最后按序输出b的0、1、2…n-1项和即可。
三、代码实现
#include<cstdio>
using namespace std;
int n=0,q=0;
int main(){
scanf("%d",&n);
scanf("%d",&q);
long long a[n]={0};
long long b[n]={0};//差分数组
for(int i=0;i<n;i++){
scanf("%lld",&a[i]);
}//a数组赋值
b[0]=a[0];
for(int i=1;i<n;i++){
b[i]=a[i]-a[i-1];
}//b数组赋值
for(int i=0;i<q;i++){
long long l=0,r=0,c=0;
scanf("%lld",&l); scanf("%lld",&r); scanf("%lld",&c);
b[l-1]+=c; b[r]-=c;
}//q次操作
long long t=b[0];
printf("%lld",b[0]);
for(int i=1;i<n;i++){
t=t+b[i];
printf(" %lld",t);
}
//输出所有值
return 0;
}
四、经验与总结
- 注意如果需要把变量都设置为long long类型,那么scanf输入、printf输出都要%lld!如果scanf输入时忘记%lld,就算输出时%lld也没有用!(并且这样写并不会有编译问题,不注意可能会遗漏)
- 根据题目数据规模,需要用long long类型时一定要用!不要想当然上int,最后会导致WA!
- 差分数组总体来说比较简单,本题的实现也较为简单,只要根据输入的a[i]求出对应的差分数组,再进行操作,最后输出,就可以得到正确的答案。
- 差分数组明显可以降低对某区间内数据做统一操作的时间复杂度,从遍历某段区间,到O(1),整体复杂度也大大降低。