[Acwing algorithm foundation] 2.5 prefix sum

One-dimensional prefix sum

  1. How to find Si: Slightly
  2. What is Si used for?
    • Quickly find the sum of the numbers in the original array

solution

Very simple

#include <iostream>

using namespace std;

const int N = 100010;

int n, m;
int a[N], s[N];

int main()
{
    
    
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
        
    for (int i = 1; i<= n; ++i)
        s[i] = s[i - 1] + a[i];
    
    while (m--)
    {
    
    
        int l, r;
        scanf("%d%d", &l, &r);
        printf("%d\n", s[r] - s[l - 1]);
    }
    
    return 0;
}

Two-dimensional prefix sum

Insert picture description here

topic

Enter an integer matrix with n rows and m columns, and then enter q queries. Each query contains four integers x1, y1, x2, y2, which represent the coordinates of the upper left corner and the lower right corner of a sub-matrix.

For each query, the sum of all numbers in the sub-matrix is ​​output.

Input format The
first line contains three integers n, m, q.

The next n rows, each row contains m integers, representing a matrix of integers.

Next line q, each line contains four integers x1, y1, x2, y2, representing a set of queries.

Output format There are
q lines in total, and each line outputs one query result.

Data range
1≤n, m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤The value of the element in the matrix≤1000
Input example:
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
Output example:
17
27
21

Code:

#include <iostream>

const int N = 1010;

int n, m, q;
int a[N][N], s[N][N];

int main()
{
    
    
    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]);
        }
    }
    
    for (int i = 1; i <= n; ++i)
    {
    
    
        for (int j = 1; j <= m; ++j)
        {
    
    
            s[i][j] = s[i - 1][j] + s[i][j-1] - 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]);
    }
    
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_22473333/article/details/114765422