题目:
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
Input:
2 1
5 -2
1 2 4
Output:
9 2
思路:
利用前缀和。
对于n个数a[1]~a[n]。
设b[1]=a[1],b[i]=a[i]-a[i-1]。则b的前缀和为对应的a[i]
对于每次操作,在区间[l,r]上加上c,b[l]+=c,b[r+1]-=c
最后累加输出b即可。
代码:
#include <stdio.h>
long long ans,a[300050],b[300050];
int n,q;
int main()
{
int l,r,c;
scanf("%d %d",&n,&q);
for(int i=1;i<=n;i++)//计算b[i]
{
scanf("%d",&a[i]);
if(i==1)
b[i]=a[i];
else
b[i]=a[i]-a[i-1];
}
for(int i=1;i<=q;i++)
{
scanf("%d%d%d",&l,&r,&c);
b[l]+=c;
b[r+1]-=c;
}
for(int i=1;i<=n;i++)
{
ans+=b[i];
printf("%d ",ans);
}
printf("\n");
return 0;
}