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]);
        }
    }
}
相关推荐
汤永红29 分钟前
week1-[分支结构]中位数
c++·算法·信睡奥赛
啊阿狸不会拉杆32 分钟前
《算法导论》第 24 章 - 单源最短路径
开发语言·数据结构·c++·算法·php
热爱生活的猴子1 小时前
算法148. 排序链表
数据结构·算法·链表
孤独得猿1 小时前
Redis类型之Hash
redis·算法·哈希算法
এ᭄画画的北北1 小时前
力扣-5.最长回文子串
算法·leetcode
点云侠2 小时前
【2025最新版】PCL点云处理算法汇总(C++长期更新版)
c++·算法·计算机视觉·3d·可视化
zaiyang遇见3 小时前
【递归完全搜索】CCC 2008 - 24点游戏Twenty-four
算法·游戏·c/c++·全排列·信息学奥赛
Python智慧行囊3 小时前
排序算法总结
数据结构·算法
似水流年流不尽思念3 小时前
常见的排序算法有哪些?它们的平均时间复杂度是多少?
后端·算法
楽码4 小时前
端到端应用Hmac加密
服务器·后端·算法