数据结构、算法总述:数据结构/算法 C/C++-CSDN博客
前缀和
前缀和可以用于快速计算一个序列的区间和,也有很多问题里不是直接用前缀和,但是借用了前缀和的思想。
一维前缀和:
S[i] = a[1] + a[2] + ... a[i]
a[l] + ... + a[r] = S[r] - S[l - 1]
for(int i = 1;i <= n;++i) s[i]=s[i-1]+a[i]; //预处理(递归)
int sum = s[r] - s[l-1]; //[l,r]的和
二维前缀和:
计算矩阵的前缀和: s [ x ][ y ] = s [ x - 1 ][ y ] + s [ x ][ y - 1 ] - s [ x - 1 ][ y - 1 ] + a [ x ][ y ]
以 ( x1 , y1 ) 为左上角, ( x2 , y2 ) 为右下角的子矩阵的和为:计算子矩阵的和: s = s [ x2 ][ y2 ] - s [ x1 - 1 ][ y2 ] - s [ x2 ][ y1 - 1 ] + s [ x1 - 1 ][ y1 - 1 ]
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
// 求前缀和
s[i][j] = s[i][j - 1] + s[i - 1][j] - s[i - 1][j - 1] + a[i][j];
}
while (q--)
{
int x1,y1,x2,y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
// 算子矩阵的和
printf("%d\n", s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1]);
}
题目:
795. 前缀和 - AcWing题库https://www.acwing.com/problem/content/797/796. 子矩阵的和 - AcWing题库
https://www.acwing.com/problem/content/798/
差分
差分是前缀和的逆运算(b是a的差分,则a是b的前缀和),对于一个数组 a ,其差分数组 b 的每一项都是 a [ i ] 和前一项 a [ i − 1 ] 的差。
一维差分
给区间[l, r]中的每个数加上c:B[l] += c, B[r + 1] -= c
for(int i=1; i<=n; i++) cin >> a[i];
for(int i=1 ;i<=n; i++) b[i] = a[i] - a[i-1];// 读入并计算差分数组
while(m--)
{
int l,r,c;
cin>>l>>r>>c;
b[l] += c;
b[r+1] -= c;// 在原数组中将区间[l, r]加上c
}
for(int i=1; i<=n; i++)
{
b[i] += b[i-1];
cout << b[i] << ' ';
}// 给差分数组计算前缀和,就求出了原数组
二维差分
给以(x1, y1)为左上角,(x2, y2)为右下角的子矩阵中的所有元素加上c:
b[x1, y1] += c, b[x2 + 1, y1] -= c, b[x1, y2 + 1] -= c, b[x2 + 1, y2 + 1] += c
void insert(int x1, int y1, int x2, int y2, int c)
{
b[x1][y1] += c;
b[x2 + 1][y1] -= c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y2 + 1] += c;
}
int main()
{
int n, m, q;
cin >> n >> m >> q;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
insert(i, j, i, j, a[i][j]); //构建差分数组
while (q--)
{
int x1, y1, x2, y2, c;
cin >> x1 >> y1 >> x2 >> y2 >> c;
insert(x1, y1, x2, y2, c);//加c
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1]; //二维前缀和
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++) printf("%d ", b[i][j]);
puts(""); // == printf("\n");
}
return 0;
}
题目:
797. 差分 - AcWing题库https://www.acwing.com/problem/content/799/798. 差分矩阵 - AcWing题库
https://www.acwing.com/problem/content/800/