前缀和算法总结(例题:激光炸弹)

前缀和思维导图:

一维前缀和算法模版:

#include <iostream>

using namespace std;

const int N = 100010;

int n, m;
int s[N];

int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
    {
        int x;
        scanf("%d", &x);
        s[i] = s[i - 1] + x;  // 前缀和的初始化
    }

    while (m--)
    {
        int l, r;
        scanf("%d%d", &l, &r);
        printf("%d\n", s[r] - s[l - 1]);  // 区间和的计算
    }

    return 0;
}

 

二维前缀和算法模版:

#include <iostream>

using namespace std;

const int N = 1010;

int n, m, q, x;
int 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", &x);
            s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x;
        }

    while (q--)
    {
        int x1, y1, x2, y2;
        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;
}

 

例题:激光炸弹

题目链接:

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

题解:

要摧毁一个包含R * R个位置的正方形((R - 1) * (R - 1)的正方形)内的所有目标,那么包围这个正方形的正方形边长至少为R。在1 <= x <= 5001,1 <= y <= 5001的范围内,枚举所有包含R * R个位置的正方形,所有这些正方形的前缀和的最大值即为答案。

代码:

#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 5010;

int s[N][N];

int main()
{
    int n, R;
    scanf("%d%d", &n, &R);
    R = min(R, 5001);
    
    for (int i = 0; i < n; i++)
    {
        int x, y, w;
        scanf("%d%d%d", &x, &y, &w);
        x++, y++;
        s[x][y] += w;
    }
    
    for (int i = 1; i <= 5001; i++)
        for (int j = 1; j <= 5001; j++)
            s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
    
    int res = 0;
    for (int i = R; i <= 5001; i++)
        for (int j = R; j <= 5001; j++)
            res = max(res, s[i][j] - s[i - R][j] - s[i][j - R] + s[i - R][j - R]);
            
    printf("%d\n", res);
    
    return 0;
}

 

posted @ 2023-11-27 19:33  ykycode  阅读(14)  评论(0编辑  收藏  举报