主要思路:
本题要求模拟给一段数列的一段区间加上数字c
由于差分描述的数组对于连续的区间加上数字c的改变很小(只是在区间边界处有所改变),所以我们用差分来处理
a = x1 - x2 = (x1 + c) - (x2 + c)
注意
- int不够,需要使用long long
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 qoperations.
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
4 2
-3 6 8 4
4 4 -2
3 3 1
Sample Output
-3 6 9 2
A Possible Solution
#include<stdio.h>
#define ll long long
ll n,q,a[200010];
int main(){
scanf("%lld %lld %lld",&n,&q,a);
ll x=a[0],y;
for(int i=1;i<n;i++){
scanf("%lld",&y);
a[i]=y-x;
x=y;
}
//for(int i=0;i<n;i++)printf("%lld ",a[i]);printf("\n");
ll l,r,c;
for(int i=0;i<q;i++){
scanf("%lld %lld %lld",&l,&r,&c);
a[l-1]+=c;
a[r]-=c;
}
ll tmp=0;
for(int i=0;i<n-1;i++){
tmp+=a[i];
printf("%lld ",tmp);
}
printf("%lld\n",tmp+a[n-1]);
return 0;
}