差分构造:计算q次操作后数组的各个元素值.c++

城市资产计算

select n cities from the world map, and a[i] represents the asset value owned by the i-th city.
Then 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.

The first line contains two integers n,qn,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 ii-th line contains three integers l,r and c(1≤l≤r≤n,−105≤c≤105) for the i-th operation.

Print nn integers a1,a2,…,an one per line, and ai should be equal to the final asset value of the i-th city

sample input/output:
在这里插入图片描述
题意:

  • 给一个长度为n的数组,共进行q次操作
  • 每次操作给出L,R,C表示在[L,R]区间内的每一个值都加上C
  • 输出在q次操作后数组中每一个元素的值

思路:

  • 本题如果直接暴力,对于每一次的操作,都直接利用循环找到L,R之间的元素然后给他们依次+C,时间复杂度是(qn),应该会超时
  • 所以利用差分构造的方式来进行解决,写出原数组的差分数组,将对区间内点的修改转变为对两个边界点的值的修改:a[l,r]+c -> b[l]+c, b[r+1]-c;
  • 最后可以利用 a[i]=a[i+1]-b[i+1] 这样的性质来逆序计算出所有数组元素的值。

差分构造

  • 设原数组为 a ,他对应的差分数组为 b
  • b[1]=a[1] , a[i]=a[i]-a[i-1]
  • b数组1~i元素的和==a数组i元素的值

在这里插入图片描述

#include<iostream>
#include<stdio.h>
using namespace std;
long long a[200011];
long long b[200011];
int main()
{
 int n,q;
 scanf("%d%d",&n,&q);
 scanf("%lld",&a[1]);
 b[1]=a[1];
 for(int i=2;i<=n;i++)
 {
  scanf("%lld",&a[i]);
  b[i]=a[i]-a[i-1];
 }
 while(q--)
 {
  int left,right;
  int c;
  scanf("%d%d%d",&left,&right,&c);
  if(left>1)
   b[left]+=c;
  if(right!=n)
   b[right+1]=b[right+1]-c;
  else 
   a[right]=a[right]+c;
 }
 for(int i=n-1;i>0;i--)
  a[i]=a[i+1]-b[i+1];
 for(int i=1;i<=n;i++)
  printf("%lld ",a[i]);
 return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值