R的取值范围比较大,可能超过边界
R有三种情况,注意边界:
- R <= min(x,y) <= max(x,y),最简单
- min(x,y) <= R <= max(x,y),正方形在矩阵滑动取值
- min(x,y) <= max(x,y) <= R,取所有值的和
由于0 <= x,y <= 5e3,所以R > 5e3无意义了。
code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 5e3+5;
int s[N][N];
int n,r;
/*
4 2
1 3 2
1 3 6
3 3 3
2 2 4
*/
int main(int argc, char** argv) {
cin >> n >> r;
int max_x= 0, max_y = 0;
// 1. 保存目标,可能一个目标多个值,累加
for(int i = 0; i < n; i++){
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
x++,y++;
if(max_x < x) max_x = x;
if(max_y < y) max_y = y;
s[x][y] += w;
}
r = min(int(5e3+1), r);
max_x = max(r,max_x);
max_y = max(r,max_y);
// 2.构造s矩阵
for(int i = 1; i <= max_x; i++)
for(int j = 1; j <= max_y; j++){
s[i][j] = s[i-1][j] + s[i][j-1] + s[i][j] - s[i-1][j-1];
}
// 3. 找最大值
int res = 0;
for(int i = r; i <= max_x; i++)
for(int j = r; j <= max_y; j++){
int tmp = s[i][j] - s[i-r][j] - s[i][j-r] + s[i-r][j-r];
res = max(tmp, max);
}
cout << res << endl;
return 0;
}