AcWing 796. 子矩阵的和

这个题的重点是仿照一维的数组,所以a[N][N]也是从1索引开始的。画个图举个例子就非常清晰了

之所以不好理解是因为没画格子,一个格子代表一个点,就很好理解了。

java代码:

java 复制代码
import java.io.*;
public class Main{
    static int N = 1010;
    static int[][] arr = new int[N][N];
    static int[][] s = new int[N][N];
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str1 = br.readLine().split(" ");
        int n = Integer.parseInt(str1[0]);
        int m = Integer.parseInt(str1[1]);
        int q = Integer.parseInt(str1[2]);
        for(int i = 1; i <= n; i++){
            String[] str2 = br.readLine().split(" ");
            for(int j = 1; j <= m; j++){
                arr[i][j] = Integer.parseInt(str2[j-1]);
            }
        }
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m;j++){
                s[i][j] = arr[i][j] + s[i-1][j] + s[i][j-1] - s[i-1][j-1];
            }
        }
        for(int i = 0 ; i < q ; i++){
        String[] str3 = br.readLine().split(" ");
        int x1 = Integer.parseInt(str3[0]);
        int y1 = Integer.parseInt(str3[1]);
        int x2 = Integer.parseInt(str3[2]);
        int y2 = Integer.parseInt(str3[3]);
        System.out.println(s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
        }
    }
}
相关推荐
yugi98783814 分钟前
基于MATLAB的延迟求和(DAS)波束形成算法实现
开发语言·算法·matlab
漫随流水21 分钟前
leetcode回溯算法(90.子集Ⅱ)
数据结构·算法·leetcode·回溯算法
Yupureki28 分钟前
《算法竞赛从入门到国奖》算法基础:搜索-记忆化搜索
c语言·c++·学习·算法·深度优先
June bug30 分钟前
(#数组/链表操作)合并两个有重复元素的无序数组,返回无重复的有序结果
数据结构·python·算法·leetcode·面试·跳槽
普贤莲花34 分钟前
取舍~2026年第4周小结---写于20260125
程序人生·算法·leetcode
curry____30342 分钟前
menset的使用方法
算法
苦藤新鸡1 小时前
39.二叉树的直径
算法·leetcode·深度优先
TracyCoder1231 小时前
LeetCode Hot100(6/100)——15. 三数之和
算法·leetcode
bubiyoushang8881 小时前
基于传统材料力学势能法的健康齿轮时变啮合刚度数值分析
人工智能·算法
星火开发设计1 小时前
const 指针与指针 const:分清常量指针与指针常量
开发语言·c++·学习·算法·指针·const·知识