题目分析:
0.二维前缀和。
1.参考蓝书22页。
code:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 5010;
int s[N][N];//前缀和矩阵
int n, m;
int main()
{
int cnt, R;
scanf("%d%d", &cnt, &R);
R = min(R, 5001);
n = m = 5001;
for(int i = 0; i < cnt; i ++)
{
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
x++, y++;//把下标映射到1~5001。右移一位, 就不需要考虑边界了,
s[x][y] += w;
}
//预处理前缀和
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];//二维前缀和公式
int res = 0;
// 枚举所有边长是R的矩形,枚举(i, j)为右下角
for(int i = R; i <= n; i ++)
for(int j = R; j <= m; 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;
}
总结:
1二维前缀和公式:
1.1 s[i][j] = s[i][j] + s[i-1][j] + s[i][j - 1] - s[i-1][j-1]
1.2 维护一个边长为R的正方形
res = s[i][j] - s[i - r][j] - s[i][j - r] + s[i - r][j - r]