AcWing 796. 子矩阵的和

解题思路

样例

1 7 2 4

3 6 2 8

2 1 2 3
求任意子矩阵的和

二维前缀和公式

相关代码

复制代码
import java.util.Scanner;

public class Main {


    public static void main(String[] args){
        //二维子矩阵的元素和
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int q = scanner.nextInt();
        int a[][] = new int[n+1][m+1];
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                a[i][j] = scanner.nextInt();

        //进行前缀和预处理
        int s[][] = new int[n+1][m+1];
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                s[i][j]=s[i][j-1]+s[i-1][j]-s[i-1][j-1]+a[i][j];


        while(q-->0){
            int x1 = scanner.nextInt();
            int y1 = scanner.nextInt();
            int x2 = scanner.nextInt();
            int y2 = scanner.nextInt();
            System.out.println(s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1]);
        }
    }
}
相关推荐
点云侠9 分钟前
【2025最新版】PCL点云处理算法汇总(C++长期更新版)
c++·算法·计算机视觉·3d·可视化
zaiyang遇见1 小时前
【递归完全搜索】CCC 2008 - 24点游戏Twenty-four
算法·游戏·c/c++·全排列·信息学奥赛
Python智慧行囊1 小时前
排序算法总结
数据结构·算法
似水流年流不尽思念1 小时前
常见的排序算法有哪些?它们的平均时间复杂度是多少?
后端·算法
楽码2 小时前
端到端应用Hmac加密
服务器·后端·算法
Morriser莫2 小时前
图论Day2学习心得
算法·图论
zyd09152 小时前
代码随想录Day50:图论(图论理论、深度搜索理论、所有可达路径、广度搜索理论)
java·数据结构·算法·leetcode·图论
Cl_rown去掉l变成C2 小时前
第R5周:天气预测
人工智能·python·深度学习·算法·tensorflow2
CoovallyAIHub3 小时前
VisDrone数据集,专为无人机视觉任务打造
深度学习·算法·计算机视觉
啊阿狸不会拉杆3 小时前
《算法导论》第 22 章 - 基本的图算法
c++·算法·排序算法·图论·拓扑学