week5作业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][l,r] and increase their asset value by cc. And finally, it is required to give the asset value of each city after q operations.
Could you help TT find the answer?
输入:
The first line contains two integers n,q(1≤n,q≤2×10^5) — the number of cities and operations.
The second line contains elements of the sequence aa: integer numbers a1,a2,…,ana1,a2,…,an (−10^ 6≤ ai ≤ 10^6)(−10 ^ 6≤ai≤10 ^6).
Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−10 ^5≤c≤10 ^5)(1≤l≤r≤n,−10 ^5≤c≤10 ^5) for the i-th operation.
输出:
Print nn integers a1,a2,…,ana1,a2,…,an one per line, and aiai should be equal to the final asset value of the ii-th city.
题目大意是给定n个城市的资产,然后进行q次操作,每次操作对[l,r]区间内的数加c,最后输出所有城市的资产。
这题如果单纯地每次对区间内每个数进行操作,因为数据范围必定会超时。而用差分数组的方法,先以O(n)的复杂度处理数组,然后就可以以O(1)的复杂度对区间的数进行操作。
差分数组B的构造方法:B[i]=A[i]-A[i-1]。这样A[j]=SUM{ B[ 0~j-1] }
如果对数组A在区间[L,R]内加C,则B[L]+=C,B[R+1]-=C即可。
以下是完整代码:

#include<iostream>
using namespace std;
long long a[300000],n,q;
long long b[300000];
int main()
{
 cin>>n>>q;
 for(int i=0;i<n;i++)
 {
  cin>>a[i];
 }
 b[0]=a[0];
 for(int i=1;i<n;i++)//差分数组 
 {
  b[i]=a[i]-a[i-1];
 } 
 int l,r,c;
 for(int i=0;i<q;i++)
 {
  cin>>l>>r>>c;
  b[l-1]=b[l-1]+c;
  b[r]=b[r]-c;
 }
 cout<<b[0]<<" ";
 long long ans=b[0];
 for(int i=1;i<n;i++)
 {
  ans=ans+b[i];
  cout<<ans<<" ";
 }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值