【算法基础】1.5 前缀和与差分

前缀和

https://www.acwing.com/problem/content/797/

题目描述

输入一个长度为 n 的整数序列。
接下来再输入 m 个询问,每个询问输入一对 l,r。
对于每个询问,输出原序列中从第 l 个数到第 r 个数的和。

在这里插入图片描述

解法

Java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt();
        int[] a = new int[n], s = new int[n + 1];
        for (int i = 0; i < n; ++i) {
            a[i] = scanner.nextInt();
            s[i + 1] = s[i] + a[i];
        }
        while (m-- > 0) {
            int l = scanner.nextInt(), r = scanner.nextInt();
            System.out.println(s[r] - s[l - 1]);
        }
    }
}

cpp

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int n, m, l, r;
    scanf("%d%d", &n, &m);
    int a[n], s[n + 1];     // s设置为n+1是为了后面计算方便
    for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
    
    s[0] = 0;
    for (int i = 0; i < n; i ++ ) s[i + 1] = s[i] + a[i];
    
    while (m -- ) {
        scanf("%d%d", &l, &r);
        printf("%d\n", s[r] - s[l - 1]);	// 这里的l和r是1~n范围
    }
    return 0;
}

讲解

在这里插入图片描述

有 a1,a2,a3,a4,a5…
想求a2+a3+a4,则只需s4-s1 = (a1+a2+a3+a4) - (a1) = a2+a3+a4。


这道题中可以不初始化 s[0] = 0,事实上,他是任何数都可以,(因为它总是会被消去)

s[i + 1] = s[i] + a[i]
s[i] 表示从 0 ~ 下标 i - 1的数字之和。

二维前缀和

题目描述——796. 子矩阵的和

https://www.acwing.com/activity/content/problem/content/830/
输入一个 n 行 m 列的整数矩阵,再输入 q 个询问,每个询问包含四个整数 x1,y1,x2,y2,表示一个子矩阵的左上角坐标和右下角坐标。

对于每个询问输出子矩阵中所有数的和。

在这里插入图片描述

解法

Java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt(), q = scanner.nextInt();
        int[][] a = new int[n][m], s = new int[n + 1][m + 1];
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                a[i][j] = scanner.nextInt();
                s[i + 1][j + 1] = a[i][j] + s[i + 1][j] + s[i][j + 1] - s[i][j];
            }
        }
        while (q-- > 0) {
            int x1 = scanner.nextInt(), y1 = scanner.nextInt(), x2 = scanner.nextInt(), y2 = scanner.nextInt();
            System.out.println(s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
        }
    }
}

Cpp

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int n, m, q, x1, y1, x2, y2;
    scanf("%d%d%d", &n, &m, &q);
    int a[n][m], s[n + 1][m + 1];
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            scanf("%d", &a[i][j]);
            s[i + 1][j + 1] = a[i][j] + s[i + 1][j] + s[i][j + 1] - s[i][j];
        }
    }
    
    while (q--) {
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        printf("%d\n", s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
    }
    
    return 0;
}

讲解

在这里插入图片描述
主要看这张图,类似于求面积。

求s:
s[i + 1][j + 1] = a[i][j] + s[i + 1][j] + s[i][j + 1] - s[i][j];

(x1,y1),(x2,y2)之间的和:
s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]

想公式想不明白的时候就想想图。

差分

https://www.acwing.com/activity/content/problem/content/831/

题目描述

输入一个长度为 n 的整数序列。

接下来输入 m 个操作,每个操作包含三个整数 l,r,c,表示将序列中 [l,r] 之间的每个数加上 c。

请你输出进行完所有操作后的序列。

在这里插入图片描述

解法1——模板写法⭐⭐⭐

先求出原始数组的差分数组 b,
然后对每个操作,l, r, c,对差分数组 b 执行

b[l] += c;
b[r + 1] -= c;

意思是从 l 开始往后的数字都要 + c
从 r + 1 开始往后的数字都要 - c,因为真实增加的数字范围只有 l ~ r ,所以要减去前面的影响。

明确 差分数组 b[i] = c,表示 a[i] 比 a[i - 1] 大 c。

Java

总结一下步骤:

  1. 先求差分数组 b
  2. 对差分数组 b 进行一系列操作
  3. 根据差分数组还原原始数组 a
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt();
        int[] a = new int[n + 1], b = new int[n + 2];
        for (int i = 1; i <= n; ++i) {
            a[i] = scanner.nextInt();   // 这里a的存储下标是从1开始的
            b[i] = a[i] - a[i - 1];     // 求差分数组
        }
        while (m-- > 0) {
            int l = scanner.nextInt(), r = scanner.nextInt(), c = scanner.nextInt();
            b[l] += c;
            b[r + 1] -= c;
        }
        for (int i = 0; i < n; ++i) {
            a[i + 1] = a[i] + b[i + 1];
            System.out.print(a[i + 1] + " ");
        }
    }
}

Cpp

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    int n, m, l, r, c;
    scanf("%d%d", &n, &m);
    int a[n + 1], b[n + 1]; // b是a的差分
    a[0] = 0;
    memset(b, 0, sizeof b);
    for (int i = 1; i <= n; i ++ ) {
        scanf("%d", &a[i]);
        b[i] = a[i] - a[i - 1];
    }
    
    while (m -- ) {
        scanf("%d%d%d", &l, &r, &c);
        b[l] += c;
        b[r + 1] -= c;
    }
    
    for (int i = 0; i < n; ++i) {
        a[i + 1] = a[i] + b[i + 1];
        printf("%d ", a[i + 1]);
    }
    
    return 0;
}

解法2——不求差分数组的写法(自己想的)

b[i] = c 表示从 0 ~ i - 1 的所有下标上的元素值都加上了 c。注意 !:这里数组 b 的定义并不是差分数组了!)

处理完数组 b 之后,从后往前遍历,就可以得到原始数组上的每个数字被影响到了多少数值。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt();
        int[] a = new int[n], s = new int[n + 1];
        for (int i = 0; i < n; ++i) a[i] = scanner.nextInt();
        while (m-- > 0) {
            int l = scanner.nextInt(), r = scanner.nextInt(), c = scanner.nextInt();
            s[r] += c;
            s[l - 1] -= c;
        }
        int sum = 0;
        // 从后往前进行遍历
        for (int i = n - 1; i >= 0; --i) {
            sum += s[i + 1];
            a[i] += sum;
        }
        for (int i = 0; i < n; ++i) System.out.print(a[i] + " ");
    }
}

后来想了一下,这种其实就是把差分数组的求法反了过来,所以遍历顺序也反了过来。

讲解

b 数组是 a 数组的差分,a 数组是 b 数组的前缀和。
那么,a中某一段变量同时变了一个数,相当于b中对应的两个数(开头和结尾)的变化。
在这里插入图片描述

二维差分⭐⭐⭐⭐⭐

题目描述——798. 差分矩阵

https://www.acwing.com/activity/content/problem/content/832/

输入一个 n 行 m 列的整数矩阵,再输入 q 个操作,每个操作包含五个整数 x1,y1,x2,y2,c,其中 (x1,y1) 和 (x2,y2) 表示一个子矩阵的左上角坐标和右下角坐标。

每个操作都要将选中的子矩阵中的每个元素的值加上 c。

请你将进行完所有操作后的矩阵输出。

在这里插入图片描述

解法

差分矩阵中
b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];

这样定义的差分矩阵有一个很好的性质,就是如果我们对某个子矩形的四个角(左上角、右上角、左下角、右下角)进行操作(加c或减c),那么当我们求原矩阵时,这个子矩形内的所有元素都会增加或减少c。这就是我们使用差分矩阵处理子矩形区间加法的原理。

java

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(), m = scanner.nextInt(), q = scanner.nextInt();
        int[][] a = new int[n + 1][m + 1], b = new int[n + 2][m + 2];
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= m; ++j) {
                a[i][j] = scanner.nextInt();
                // 求差分矩阵
                b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];
            }
        }
        // 对差分数组进行操作
        while (q-- != 0) {
            int x1 = scanner.nextInt(), y1 = scanner.nextInt(), x2 = scanner.nextInt(), y2 = scanner.nextInt(), c = scanner.nextInt();
            b[x1][y1] += c;
            b[x2 + 1][y2 + 1] += c;
            b[x2 + 1][y1] -= c;
            b[x1][y2 + 1] -= c;
        }
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                a[i + 1][j + 1] = - a[i][j] + a[i + 1][j] + a[i][j + 1] + b[i + 1][j + 1];
                System.out.print(a[i + 1][j + 1] + " ");
            }
            System.out.println();
        }
    }
}

要记住中间的重要代码。

cpp

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1005;
int a[N][N], b[N][N];	// 开大一点可以减少越界的麻烦

int main()
{
    int n, m, q, x1, y1, x2, y2, c;
    scanf("%d%d%d", &n, &m, &q);
    
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            scanf("%d", &a[i][j]);
            b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];
        }
    }
    
    while (q -- ) {
        scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &c);
        b[x1][y1] += c;
        b[x2 + 1][y2 + 1] += c;
        b[x1][y2 + 1] -= c;
        b[x2 + 1][y1] -= c;
    }
    
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            a[i][j] = b[i][j] + a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
    
    return 0;
}

讲解

这里同样可以在脑海中想象那个正方形来帮助写代码。
请添加图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wei *

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值