TT's Magic Cat

魔法猫考验TT的能力,通过一系列操作改变城市资产值,挑战在于高效计算多次区间增加后的最终资产值。采用差分数组优化算法,实现快速求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

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?

输入输出要求:
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 a: integer numbers a1,a2,…,an (−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) for the i-th operation.

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

样例输入1:

4 2
-3 6 8 4
4 4 -2
3 3 1

样例输出1:

-3 6 9 2

样例输入2:

2 1
5 -2
1 2 4

样例输出2:

9 2

样例输入3:

1 2
0
1 1 -8
1 1 -6

样例输出3:

-14

思路:

暴力做法:
直接循环,将[l,r]中的每个数依次+c,进行q次操作,复杂度为O(qn),超时

差分:
本题明显是对一个区间的数据进行操作,利用差分的特点,将A数组区间的操作改为对B数组的单点操作

差分构造方式
原数组 A,差分数组 B, 数组范围 [1, n]
• B[1] = A[1]
• B[i] = A[i] - A[i-1]
差分特点
• B 数组前缀和⇔A 数组元素值
SUM{B[1~i]} = A[i]
• A 数组的区间加⇔B 数组的单点修改
A[L]~A[R] 均加上 c 等价于 B[L] += c, B[R+1] -= c

解题:
由上面的分析,将the asset value owned by the i-th city构造成A数组,并获得其差分数组,将A的区间变化转化为B的端点变化

总结:

1.能够根据“区间变化->端点变化“判断出使用差分数组
2.差分数组求sum,保险起见使用long long型数据

代码:

#include<iostream>
using namespace std;

int n,q,l,r,c;
long long a[200010],b[200010],b_sum[200010];

int main(){
	cin>>n>>q;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		if(i==1)  b[i]=a[i];
		else  b[i]=a[i]-a[i-1];	
	}
	for(int i=0;i<q;i++){
		cin>>l>>r>>c;
		b[l]+=c;
		b[r+1]-=c;
	}
	for(int i=1;i<=n;i++){
		b_sum[i]=b_sum[i-1]+b[i];
		if(i!=n) cout<<b_sum[i]<<" ";
		else cout<<b_sum[i]<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值