侧边栏壁纸
博主头像
CoderKui

坐中静,舍中得,事上练

  • 累计撰写 51 篇文章
  • 累计创建 69 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

前缀和

CoderKui
2021-11-27 / 0 评论 / 0 点赞 / 280 阅读 / 926 字 / 正在检测是否收录...

前缀和

元素:a1, a2, a3, a4, ..., an

前缀和:Si = a1 + a2 + ... + ai (S0 = 0)

  1. 如何求Si

    递推:Si = Si-1 + ai

  2. 有什么用

    快速求原数组中[l, r]段的和,如果没有前缀和,至少需要循环遍历一次,是O(n)的时间复杂度,

    而有了前缀和:[l, r]段的和 = Sr - Sl-1 ,达到O(1)实现求区间和

前缀和看起来简单,实际上用途非常广,更多时候它是一种思想,不要被求和给限制了,且可以推广至二维情况。

一维前缀和应用例子:

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

接下来再输入 mm 个询问,每个询问输入一对 l,rl,r。

对于每个询问,输出原序列中从第 ll 个数到第 rr 个数的和。

输入格式

第一行包含两个整数 nn 和 mm。

第二行包含 nn 个整数,表示整数数列。

接下来 mm 行,每行包含两个整数 ll 和 rr,表示一个询问的区间范围。

输出格式

共 mm 行,每行输出一个询问的结果。

数据范围

1≤l≤r≤n1≤l≤r≤n,
1≤n,m≤1000001≤n,m≤100000,
−1000≤数列中元素的值≤1000−1000≤数列中元素的值≤1000

输入样例:

5 3
2 1 3 6 4
1 2
1 3
2 4

输出样例:

3
6
10
import java.util.*;

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


二维前缀和应用例子:

输入一个 nn 行 mm 列的整数矩阵,再输入 qq 个询问,每个询问包含四个整数 x1,y1,x2,y2x1,y1,x2,y2,表示一个子矩阵的左上角坐标和右下角坐标。

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

输入格式

第一行包含三个整数 n,m,qn,m,q。

接下来 nn 行,每行包含 mm 个整数,表示整数矩阵。

接下来 qq 行,每行包含四个整数 x1,y1,x2,y2x1,y1,x2,y2,表示一组询问。

输出格式

共 qq 行,每行输出一个询问的结果。

数据范围

1≤n,m≤10001≤n,m≤1000,
1≤q≤2000001≤q≤200000,
1≤x1≤x2≤n1≤x1≤x2≤n,
1≤y1≤y2≤m1≤y1≤y2≤m,
−1000≤矩阵内元素的值≤1000−1000≤矩阵内元素的值≤1000

输入样例:

3 4 3
1 7 2 4
3 6 2 8
2 1 2 3
1 1 2 2
2 1 3 4
1 3 3 4

输出样例:

17
27
21
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int q = sc.nextInt();
        int[][] area = new int[n + 1][m + 1];
        int[][] pre = new int[n + 1][m + 1];
        for(int i = 1; i <= n; ++i) {
            for(int j = 1; j <= m; ++j) {
                area[i][j] = sc.nextInt();
            }
        }
        for(int i = 1; i <= n; ++i) { // 求前缀和
            for(int j = 1; j <= m; ++j) {
                pre[i][j] = pre[i - 1][j] + pre[i][j - 1] - pre[i - 1][j - 1] + area[i][j];
            }
        }
        while(q-- > 0) {
            int x1 = sc.nextInt();
            int y1 = sc.nextInt();
            int x2 = sc.nextInt();
            int y2 = sc.nextInt();
            int res = pre[x2][y2] - pre[x1 - 1][y2] - pre[x2][y1 - 1] + pre[x1 - 1][y1 - 1]; // 计算子矩阵
            System.out.println(res);
        }
    }
}
0

评论区