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?
二、输入
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.
三、输出
Print n integers a1,a2,…,an one per line, and ai should be equal to the final asset value of the i-th city.
四、样例输入输出
Input
4 2
-3 6 8 4
4 4 -2
3 3 1
Output
-3 6 9 2
五、解题思路
前缀和和差分。
利用差分思想将a【i-1】-a【i】存放进b数组,将每次对a数组区间的操作转变为对b数组的单点操作。例如对a区间【2,5】操作+3,就可以转为对b【1】-3,b【5】操作+3。在结束时通过a【i】=b【i】+a【i-1】即可还原a数组。
通过这种方法可以大量减少对数组中元素的操作次数。
六、代码样例
#include<stdio.h>
long long int a[210000];
long long int b[210000];
int main()
{
int n;scanf("%d",&n);
int q;scanf("%d",&q);
scanf("%lld",&a[0]); //读入第一个数
b[0]=a[0];
for(int i=1;i<n;i++) //读入剩下的数
{
scanf("%lld",&a[i]);
b[i]=a[i]-a[i-1];
}
int l,r,c;
for(int i=0;i<q;i++)
{
scanf("%d %d %d",&l,&r,&c);
b[l-1]+=c;
b[r]-=c;
}
a[0]=b[0];
for(int i=1;i<n;i++)
{
a[i]=a[i-1]+b[i];
}
printf("%lld ",a[0]);
for(int i=1;i<n;i++) printf("%lld ",a[i]);
}