程序设计思维 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?

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

Input
4 2
-3 6 8 4
4 4 -2
3 3 1
Output
-3 6 9 2

Input
2 1
5 -2
1 2 4
Output
9 2

Input
1 2
0
1 1 -8
1 1 -6
Output
-14

题意

长度为 n 的数组,一共 q 次操作 (1≤n,q≤2⋅105),每次操作给出 L, R , c,表示区间 [L, R] 中各个数均加 上 c ,求 q 次操作结束后,数组中各个元素值?

思路

和A题一样,需要用到 long long 型数据。
一、差分
将输入的a1,a2,…,an存放到数组a中,同时设a[0] = 0。
定义差分数组dif为dif[i] = a[i] - a[i-1]。
例如,设a = {0, 2, 6, 8, 4, 3},dif如图:
在这里插入图片描述
假设L = 2,R = 4,c = 5,则a[L]~a[R]同时加上c后的数组a和相应的数组dif如图:
在这里插入图片描述
可以发现,dif[3]~dif[4]不变,而dif[2] = dif[2] + c、dif[5] = dif[5] - c:
在这里插入图片描述
类似地,可以证明:当数组a[L]~a[R]同时加上c时,数组dif中dif[L+1]到dif[R]不变,而dif[L] = dif[L] + c、dif[R+1] = dif[R+1] - c。
故进行q次操作时,每次操作只需要改变两个数:dif[L]和dif[R+1],而无需将dif[L]到dif[R]逐个加c,极大地减小了时间复杂度。
二、前缀和
前缀和相当于差分的逆运算,将数组dif还原回数组a:
在这里插入图片描述
关系公式:a[i] = dif[i] + a[i-1]。

代码

#include <iostream>
#define MAX 1000000

using namespace std;

long long int n, q;
long long int a[MAX];
long long int dif[MAX];

int main()
{
	cin >> n >> q;
	for (int i = 1; i <= n; i++)cin >> a[i];
	a[0] = 0;

	dif[0] = 0;
	for (int i = 1; i <= n; i++) dif[i] = a[i] - a[i - 1];

	for (int i = 0; i < q; i++) {
		int left, right;
		long long int c;
		cin >> left >> right >> c;
		dif[left] += c;
		dif[right + 1] -= c;
	}

	long long int cnt = 0;

	for (int i = 1; i <= n; i++) {
		cnt += dif[i];
		cout << cnt << " ";
	}
	cout << endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值