题意: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?
思路:对于对某段区间内每个数进行多次加某个数,
不需要依次遍历,可以利用差分,对区间l-r一段区间内a[i]都+c 相当于差分b[l]=b[l]+c b[r+1]=b[r+1]-c;
差分公式b[i]=a[i]-a[i-1] 这样sum(b[i])等于a[i]
总结:该题是典型的差分应用
代码:
//差分
#include<iostream>
#include<cstdio>
using namespace std;
int city[200010];
long long sum[200010];
int main()
{ int n,q;scanf("%d%d",&n,&q);city[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&city[i]);
sum[i]=city[i]-city[i-1];//差分公式b[i]=a[i]-a[i-1] 这样sum(b[i])等于a[i]
}
for(int i=1;i<=q;i++)
{
int l,r,c;scanf("%d%d%d",&l,&r,&c);
sum[l]+=c;sum[r+1]-=c;//l-r一段区间内a[i]都+c 相当于差分b[l]=b[l]+c b[r+1]=b[r+1]-c;
}
long long ssum=0;
for(int i=1;i<=n;i++)
{
ssum=ssum+sum[i];
printf("%lld ",ssum);
}
return 0;
}