C++ laser bomb (two-dimensional prefix sum)

There are N targets on the map. Use integers Xi, Yi to represent the position of the target on the map. Each target has a value Wi.
Note: Different targets may be in the same location.
There is a new type of laser bomb that can destroy all targets in a square containing R×R positions.
The delivery of laser bombs is located by satellites, but it has a disadvantage that its explosion range, that is, the sides of the square must be parallel to the x and y axes.
If the target is on the side of the blasting square, the target will not be destroyed.
What is the maximum value of the target on the map that can be destroyed by a bomb.
Input format
Enter the positive integers N and R on the first line, which represent the number of targets on the map and the side length of the square, respectively. The data are separated by spaces.
In the next N lines, enter a set of data in each line. Each set of data includes three integers Xi, Yi, Wi, which represent the x-coordinate, y-coordinate and value of the target, and the data are separated by spaces.
Output format
Output a positive integer, which represents the total value of a bomb that can blow up the target on the map.
Data range
0≤R≤109
0<N≤10000,
0≤Xi,Yi≤5000
0≤Wi≤1000
Input example:
2 1
0 0 1
1 1 1
Output example:
1

AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

int n,r;
int X=0,Y=0;
int s[5010][5010];
int ans=0;

int main()
{
    
    
    scanf("%d%d",&n,&r);
    r=min(5001,r);
    int x,y;
    int num;
    X=Y=r;
    while(n--)
    {
    
    
        scanf("%d%d%d",&x,&y,&num);
        ++x;++y;
        s[x][y]+=num;//不同目标可能在同一位置
        X=max(X,x);Y=max(Y,y);
    }
    for(int i=1;i<=X;++i)//求前缀和
    {
    
    
        for(int j=1;j<=Y;++j)
            s[i][j]+=s[i][j-1]+s[i-1][j]-s[i-1][j-1];
    }
    for(int i=r;i<=X;++i)//枚举r*r正方形
    {
    
    
        for(int j=r;j<=Y;++j)
        {
    
    
            //s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1]
            //x1是i-(r-1),y1是j-(r-1)
            ans=max(ans,s[i][j]-s[i][j-r]-s[i-r][j]+s[i-r][j-r]);
        }
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108815740