当前位置:网站首页>【10. 差分】
【10. 差分】
2022-06-27 07:42:00 【小呆鸟_coding】
一维差分
- 前缀和与差分是逆运算
例如:
数组 a1 , a2,a3,a4,a5 ,…,an
构造 b1,b2,b3,b4,b5,…,bn
使得 ai = b1 + b2 + b3 + b4 + … + bi。c此时 ai叫做 bi的前缀和,b 叫做 ai的差分.
差分的用途:
前缀和主要是计算数组中的某个区间 [ l, r ],中间的所有数的和。
而差分主要是为了计算在[ l, r ]这个区间中所有的数全部加上一个常数c。优点:
正常遍历数组中[ l , r ]区间的话,需要的是o(n)的复杂度,但是使用差分直接是o(1)的复杂度。差分只需要俩步计算。
步骤:
- 要对数组 a的
[ l , r]区间的所有数全部加 +1,等价于b[ l ] + 1,(因为a数组是b数组的前缀和,bl +1,相当于把数组a中下标 > l 的所有数全部 +1)- 但是我们希望的是
只对[ l , r]这个区间数+1,经过上述运算,r后面的数也同时 +1,此时通过b[ r + 1]进行 -1 操作。
图解
题目
输入一个长度为 n 的整数序列。
接下来输入 m 个操作,每个操作包含三个整数 l,r,c,表示将序列中 [l,r][l,r] 之间的每个数加上 c。
请你输出进行完所有操作后的序列。
输入格式
第一行包含两个整数 n 和 m。
第二行包含 n 个整数,表示整数序列。
接下来 m 行,每行包含三个整数 l,r,c表示一个操作。
输出格式
共一行,包含 n 个整数,表示最终序列。
数据范围
1 ≤ n,m ≤ 100000
1 ≤ l ≤ r ≤ n
−1000 ≤ c ≤ 1000
−1000 ≤ 整数序列中元素的值 ≤1000输入样例:
6 3 1 2 2 1 2 1 1 3 1 3 5 1 1 6 1输出样例:
3 4 5 3 4 2
代码
#include <iostream> using namespace std; const int N = 100010; int n, m; int a[N], b[N], s[N]; void insert(int l, int r, int c) //核心公式 { b[l] += c; b[r + 1] -= c; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i ++) scanf("%d", &a[i]); while (m --) { int l, r, c; scanf("%d%d%d", &l, &r, &c); insert(l, r, c); } for (int i = 1; i <= n; i ++) b[i] += b[i - 1] ; //前缀和公式 for (int i = 1; i <= n; i ++) { a[i] += b[i]; cout << a[i] << " "; } return 0; }
边栏推荐
猜你喜欢

JS print 99 multiplication table

JS find the number of all daffodils

Remote connection raspberry pie in VNC Viewer Mode

How to view program running time (timer) in JS

语音信号处理-概念(二):幅度谱(短时傅里叶变换谱/STFT spectrum)、梅尔谱(Mel spectrum)【语音的深度学习主要用幅度谱、梅尔谱】【用librosa或torchaudio提取】

JS to determine whether the result is qualified, the range is 0-100, otherwise re-enter

JS use switch to output whether the result is qualified

多表联查--07--- Hash join

VNC Viewer方式的远程连接树莓派

Error in idea connection database
随机推荐
Mobile security tools -jad
Difference between boundvalueops and opsforvalue
多表联查--07--- Hash join
MSSQL how to export and delete multi table data using statements
剑指 Offer 07. 重建二叉树
volatile 和 synchronized 到底啥区别?
通过uview让tabbar根据权限显示相应数量的tabbar
期货反向跟单—交易员的培训问题
Speech synthesis: tacotron explains [end-to-end speech synthesis model] [compared with traditional speech synthesis, it does not have complex phonetics and acoustic feature modules, but only uses < te
Manim math engine
Guava tutorial collect some cases and write Google tool classes slowly
R 语言 基于关联规则与聚类分析的消费行为统计
二叉树结构以及堆结构基础
jupyter notebook文件目录
JS use the switch statement to output the corresponding English day of the week according to 1-7
How can I import data from Oracle into fastdfs?
Guava scheduled task
1-4 进制表示与转换
1-4 decimal representation and conversion
什么是期货反向跟单?
