题目大意:

给出一个5000×50005000×5000的矩阵,每个格子上都有权值,求用一个n×nn×n的框最多能框住多少?


思路;

考虑二位维前缀和,设s[i][j]s[i][j]为以(1,1)(1,1)为左上角,(i,j)(i,j)为右下角的矩阵的和。那么根据容斥原理,易得:

s[i][j]=s[i1][j]+s[i][j1]s[i1][j1]+a[i][j]s[i][j]=s[i−1][j]+s[i][j−1]−s[i−1][j−1]+a[i][j]

那么再枚举正方形的右下角求出每个矩阵的答案,再取最大值即可。
ans=max(s[i][j]s[im][j]s[i][jm]+s[im][jm])ans=max(s[i][j]−s[i−m][j]−s[i][j−m]+s[i−m][j−m])


代码:

#include <cstdio>
#include <iostream>
using namespace std;

int n,m,s[5011][5011],x,y,lenn,lenm,ans;

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
    {
        scanf("%d%d",&x,&y);
        scanf("%d",&s[x+1][y+1]);
    }
    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]+s[i][j];  //二维前缀和
    for (int i=m;i<=5001;i++)
     for (int j=m;j<=5001;j++)
      ans=max(ans,s[i][j]-s[i-m][j]-s[i][j-m]+s[i-m][j-m]);
    printf("%d\n",ans);
    return 0;
}