# 前缀和算法总结（例题：激光炸弹）

#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/

#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  阅读(9)  评论(0编辑  收藏  举报