前缀和

Posted by 磊落 on May 11, 2020

前缀和

思想

  • 原数组 a1, a2, a3, a4, a5, …, an

  • 前缀和 Si = a1 + a2 + a3 + … + ai (i = 1~n)

一维特点

  1. 规定:S0 = 0,所有待求数组下标都是从1开始

  2. Si = Si-1 + ai

  3. 求[l, r]区间内所有值之和 sum = Sr - Sl-1

二维特点

  1. s[i][j] = s[i][j - 1] + s[i - 1][j] - s[i - 1][j - 1] + a[i][j];

  2. int res = s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1];

// 一维
#include <iostream>
#include <algorithm>

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;
}




//二维
#include <iostream>
#include <algorithm>

using namespace std;

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][j - 1] + s[i - 1][j] - s[i - 1][j - 1] + a[i][j];
    
    int x1, y1, x2, y2;
    while (q--)
    {
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        int res = s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1];
        printf("%d\n", res);
    }

    return 0;
}