Problem:
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 nn cities from the world map, and a[i]a[i] represents the asset value owned by the ii-th city.
Then the magic cat will perform several operations. Each turn is to choose the city in the interval [l,r][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,qn,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 aa: integer numbers a1,a2,...,ana1,a2,...,an (−106≤ai≤106)(−106≤ai≤106).
Then qq lines follow, each line represents an operation. The ii-th line contains three integers l,rl,r and cc (1≤l≤r≤n,−105≤c≤105)(1≤l≤r≤n,−105≤c≤105) for the ii-th operation.
Output
Print nn integers a1,a2,…,ana1,a2,…,an one per line, and aiai should be equal to the final asset value of the ii-th city.
Examples
1 Input
2 4 2
3 -3 6 8 4
4 4 4 -2
5 3 3 1
6 Output
7 -3 6 9 2
8 Input
9 2 1
10 5 -2
11 1 2 4
12 Output
13 9 2
14 Input
15 1 2
16 0
17 1 1 -8
18 1 1 -6
19 Output
20 -14
My Solution:
本题一般做法较复杂(TLE)
利用前缀和的思路来解决。 我们另外需要一个数组来记录前缀和变化。
对于给定区间,我们在记录前缀和的数组做相应变化(左端-1加常数,右端减常数)而不必每次对所有区间内的数操作。
这样最后遍历原始,只需要加上相应的前缀和即可!
1 #include<iostream>
2 #include<cstdio>
3 #include<string.h>
4 using namespace std;
5
6 long long a[200002];
7 long long b[200002]; //a为原数组,b为差分数组
8
9 int main(){
10 long long n,q,l,r,c;
11 //cin>>n>>q;
12 scanf("%lld%lld",&n,&q);
13 memset(a,0,sizeof(a));
14
15 for(int i=1;i<=n;i++) scanf("%lld",&a[i]);//cin>>a[i];
16
17 for(int i=1;i<=n;i++)
18 b[i]=a[i]-a[i-1];
19
20 for(int op=1;op<=q;op++)
21 {
22 scanf("%lld%lld%lld",&l,&r,&c);
23 b[l]+=c;
24 b[r+1]-=c;
25 }
26
27 long long ans=0;
28 for(int i=1;i<n;i++)
29 {
30 ans+=b[i];
31 printf("%lld ",ans);
32 }
33 printf("%lld\n",ans+b[n]);
34
35 //cout<<a[i]<<endl;
36 return 0;
37 }