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.
Sample Input 1
2 1
5 -2
1 2 4
Sample Output 1
9 2
Sample Input 2
4 2
-3 6 8 4
4 4 -2
3 3 1
Sample Output 2
-3 6 9 2
Sample Input 3
1 2
0
1 1 -8
1 1 -6
Sample Output 3
-14
题解
- 采用前缀和与差分的方法
- 用另一个数组存放原数组的差分,b[1]=a[1],b[i]=a[i]-a[i-1]。在a中一段区间内所有数字加一个相同的数,则只需改变b[left]和b[right+1]即可。最后求b的前缀和并输出。
- 有些题目用G++会超时,C++却不会。
坑点
注意数据大小,用long long。
代码
#include <iostream>
#include <stdio.h>
using namespace std;
long long city[300000],sub[300000];
int main(int argc, char** argv) {
int n,t;//n个城市,t次操作
scanf("%d %d",&n,&t);
city[0]=0;
for(int i=1;i<=n;i++){
scanf("%lld",&city[i]);
sub[i]=city[i]-city[i-1];
}
for(int i=0;i<t;i++){
int change,l,r;
scanf("%d %d %d",&l,&r,&change);
sub[l]+=change;
sub[r+1]-=change;
}
long long print=0;
for(int i=1;i<=n;i++){
print=print+sub[i];
printf("%lld ",print);
}
return 0;
}