城市资产计算
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;
}