AcWing 99. 激光炸弹 (二维前缀和)

99. 激光炸弹

题意

  • 给定一个5000x5000的地图
  • 随机在该地图上放置物品,物品具有价值,且不同物品可以放置在同一位置
  • 有一个炸弹的爆炸范围为RxR的正方形
  • 问该炸弹在地图上爆炸一次,最多能摧毁的物品价值为多少

思路

  • 枚举该正方形在地图中所有可能出现的位置
  • 利用二维前缀和计算在正方形范围内物品的价值和
  • 找出最大的那一个价值和
class Main {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String[] split;
    // 目标数与正方形边长
    int n, r;
    // 目标坐标与权值
    int x, y, w;
    // 地图
    int[][] map = new int[5010][5010];
    
    // 前缀和矩阵
    int[][] S = new int[5010][5010];
    
    void run() throws Exception {
        split = reader.readLine().split(" ");
        
        n = Integer.parseInt(split[0]);
        r = Integer.parseInt(split[1]);
        
        while (n-- > 0) {
            split = reader.readLine().split(" ");
            
            x = Integer.parseInt(split[0]);
            y = Integer.parseInt(split[1]);
            w = Integer.parseInt(split[2]);
            
            // 输入的坐标(0, 0) 相当于 map中(1, 1)
            map[x +  1][y +  1] += 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] + map[i][j];
            }
        }
        
        int res = -Integer.MAX_VALUE;
        // 枚举正方形在地图中出现的位置,(i, j)是正方形的右上角坐标
        for (int i = 1; i <= 5001; i++) {
            if (i + r - 1 > 5001) break;
            for (int j = 1; j <= 5001; j++) {
                if (j + r - 1 > 5001) break;
                
                // 计算出正方形右下角坐标,然后通过前缀和矩阵计算子矩阵和
                int x1 = i, y1 = j;
                int x2 = i + r - 1, y2 = j + r - 1;

                int sum = S[x2][y2] - S[x1 - 1][y2] - S[x2][y1 - 1] + S[x1 - 1][y1 - 1];
                
                res = Math.max(sum, res);
            }
        }
        System.out.println(res);
    }
    
    public static void main(String[] args) throws Exception { new Main().run(); }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值