AcWing 796. 子矩阵的和
发布日期:2021-05-07 14:08:21 浏览次数:21 分类:精选文章

本文共 1444 字,大约阅读时间需要 4 分钟。

输入一个n行m列的整数矩阵,再输入q个询问,每个询问包含四个整数x1, y1, x2, y2,表示一个子矩阵的左上角坐标和右下角坐标。

对于每个询问输出子矩阵中所有数的和。

输入格式

第一行包含三个整数n,m,q。

接下来n行,每行包含m个整数,表示整数矩阵。

接下来q行,每行包含四个整数x1, y1, x2, y2,表示一组询问。

输出格式

共q行,每行输出一个询问的结果。

数据范围

1≤n,m≤10001≤n,m≤1000,

1≤q≤2000001≤q≤200000,
1≤x1≤x2≤n1≤x1≤x2≤n,
1≤y1≤y2≤m1≤y1≤y2≤m,
−1000≤矩阵内元素的值≤1000−1000≤矩阵内元素的值≤1000

输入样例:

3 4 31 7 2 43 6 2 82 1 2 31 1 2 22 1 3 41 3 3 4

输出样例:

172721
import java.io.*;import java.lang.*;class Main{        public static void main(String[] args)throws Exception{        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));        String[] input = buf.readLine().split(" ");        int n = Integer.valueOf(input[0]);        int m = Integer.valueOf(input[1]);        int q = Integer.valueOf(input[2]);        int[][] mat = new int[n + 1][m + 1];        for(int i = 1; i <= n; ++i){//构建前缀矩阵            String[] info = buf.readLine().split(" ");            for(int j = 1; j <= m; ++j)                mat[i][j] = Integer.valueOf(info[j - 1]) + mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1];        }        for(int i = 0; i < q; ++i){            String[] info = buf.readLine().split(" ");            int x1 = Integer.valueOf(info[0]);            int y1 = Integer.valueOf(info[1]);            int x2 = Integer.valueOf(info[2]);            int y2 = Integer.valueOf(info[3]);            System.out.println(mat[x2][y2] - mat[x1 - 1][y2] - mat[x2][y1 - 1] + mat[x1 - 1][y1 - 1]);        }       }}

 

上一篇:AcWing 797. 差分
下一篇:AcWing 795. 前缀和

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年03月22日 23时53分54秒