题目
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 cc
. And finally, it is required to give the asset value of each city after qq
operations.Could you help TT find the answer?
Input
The first line contains two integers n,q
(1≤n,q≤2⋅105)(1≤n,q≤2·105)— the number of cities and operations.The second line contains elements of the sequence a integer numbers a1,a2,…,ana1,a2,…,an
(−106≤ai≤106)(−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)(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 ii
-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
思路:
直接暴力求解的话复杂度为O(qn),数据太大的话会超时,所以我们定义a的差分数组b,b[1]=a[1],b[i]=a[i]-a[i-1],那么a从l到r都加上c就变成为b[l]+=c,b[r+1]-=c,这样复杂度就变成了O(n+q),然后再a[i]=b[i]+a[i-1]求a即可
代码
#include <iostream>
using namespace std;
int main()
{
long long a[200005];
long long b[200005];
int n,p;
cin>>n>>p;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
b[1]=a[1];
for(int i=2;i<=n;i++)
{
b[i]=a[i]-a[i-1];
}
for(int i=0;i<p;i++)
{
int l,r,c;
cin>>l>>r>>c;
b[l]+=c;
b[r+1]-=c;
}
a[1]=b[1];
cout<<a[1]<<" ";
for(int i=2;i<=n;i++)
{
a[i]=a[i-1]+b[i];
if(i==n)
cout<<a[i]<<endl;
else
cout<<a[i]<<" ";
}
return 0;
}