程序设计思维与实践 Week5 作业 B-TT's Magic Cat

题目链接: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] 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?

世界地图上有n个城市,a[i]表示第i个城市所拥有的价值,对于某段区间[l,r]内的城市,每次操作对于它们的价值加上c,求q次操作后的各个城市价值结果。

Input:
The first line contains two integers n,q (1≤n,q≤2⋅1e5) — the number of cities and operations.
The second line contains elements of the sequence a: integer numbers a1,a2,…,an (−1e6≤ai≤1e6).
Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−1e5≤c≤1e5) for the i-th operation.

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

Sample Input-1:
4 2
-3 6 8 4
4 4 -2
3 3 1

Sample Output-1:
-3 6 9 2

Sample Input-2:
2 1
5 -2
1 2 4

Sample Output-2:
9 2

Sample Input-3:
1 2
0
1 1 -8
1 1 -6

Sample Output-3:
-14

思路:
对于维护区间信息的数据结构有线段树,树状数组等,而对于每次对一个区间进行加或着减,最后求每个点的值,差分标记是最合适的。开始初始化为0的sum数组,每次操作输入区间[l,r],以及增加的价值c,使得sum[l]+=c;sum[r+1]-=c,最后设置一个变量,在循环sum数组时每次用res加上sum[i],即可得到每个城市更新后的价值。

总结:
差分法对于某段区间进行加减操作时比较优化的数据结构,也是对特定题型有着很强的适用性。

代码:

#include<iostream>
using namespace std;
int a[1000010],sum[1000010];
int n,q,l,r,c;
int res=0;
int main(){
	cin>>n>>q;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		sum[i]=a[i]-a[i-1];
	}
	while(q--){
		cin>>l>>r>>c;
		sum[l]+=c;
		sum[r+1]-=c;
	}
	for(int i=1;i<=n;i++){
		res+=sum[i];
        cout<<res<<" ";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值