[Basic algorithm notes] Prefix sum

 A brief summary of learning algorithms on acwing


One-dimensional prefix sum

Analysis: You can compare it to the S(n) - S(m-1) you learned in high school. What you want to find is the sum of the m term to the nth term of the sequence a. The same idea is used when migrating to code.

Core: s[i] = s[i - 1] + a[i] (continuously accumulating the values ​​in the a array)

#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

We represent this integer matrix as a square diagram to make it easier to understand.

Then we have to solve how to find the sum of all the numbers in the submatrix. Since one dimension has been increased, the expression of the prefix sum will also correspond to one more dimension. Originally, only one direction was considered in one dimension, but in a two-dimensional plan view, we can divide it into two directions: horizontal and vertical. As shown in the figure below s [ 2 ] [ 3 ] = s [ 1 ] [ 3 ] + s [ 2 ] [ 2 ] + a [ 2 ] [ 3 ] - s [ 1 ] [ 1 ]

The generalization is s[i][j] = s[i-1][j] + s[i][j-1] + a[i][j] - s[i-1][j-1]

Next, continue to generalize the formula for the sum of sub-matrices as s[x2,y2]−s[x1−1,y2]−s[x2,y1−1]+s[x1−1,y1−1]

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

using namespace std;
const int N = 1010;
int a[N][N], s[N][N];
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 ++ )
            s[i][j] = s[i-1][j] + s[i][j-1] + a[i][j] - s[i-1][j-1];
            
    while(q--)
    {
        int x1,x2,y1,y2;
        cin>>x1>>y1>>x2>>y2;
        cout<<s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1]<<endl;
    }
}

おすすめ

転載: blog.csdn.net/Radein/article/details/134867686