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]);
        }
    }
}
相关推荐
FogLetter14 分钟前
微信红包算法揭秘:从随机性到产品思维的完美结合
算法
BUG收容所所长40 分钟前
二分查找的「左右为难」:如何优雅地找到数组中元素的首尾位置
前端·javascript·算法
itsuifengerxing1 小时前
python 自定义无符号右移
算法
猎板PCB厚铜专家大族2 小时前
高频 PCB 技术发展趋势与应用解析
人工智能·算法·设计规范
dying_man2 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel2 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
草莓熊Lotso3 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM3 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法
CV点灯大师3 小时前
C++算法训练营 Day10 栈与队列(1)
c++·redis·算法
GGBondlctrl3 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想