差分应用(题解)

题意: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;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值