AcWing 798. 差分矩阵
发布日期:2021-05-07 14:08:22 浏览次数:10 分类:原创文章

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

输入一个n行m列的整数矩阵,再输入q个操作,每个操作包含五个整数x1, y1, x2, y2, c,其中(x1, y1)和(x2, y2)表示一个子矩阵的左上角坐标和右下角坐标。

每个操作都要将选中的子矩阵中的每个元素的值加上c。

请你将进行完所有操作后的矩阵输出。

输入格式

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

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

接下来q行,每行包含5个整数x1, y1, x2, y2, c,表示一个操作。

输出格式

共 n 行,每行 m 个整数,表示所有操作进行完毕后的最终矩阵。

数据范围

1≤n,m≤10001≤n,m≤1000,
1≤q≤1000001≤q≤100000,
1≤x1≤x2≤n1≤x1≤x2≤n,
1≤y1≤y2≤m1≤y1≤y2≤m,
−1000≤c≤1000−1000≤c≤1000,
−1000≤矩阵内元素的值≤1000−1000≤矩阵内元素的值≤1000

输入样例:

3 4 31 2 2 13 2 2 11 1 1 11 1 2 2 11 3 2 3 23 1 3 4 1

输出样例:

2 3 4 14 3 4 12 2 2 2
import java.io.*;import java.lang.*;class Main{        static void diff(int[][] b, int i, int j, int k){//构造差分矩阵        b[i][j] += k;        b[i + 1][j] -= k;        b[i][j + 1] -= k;        b[i + 1][j + 1] += k;    }    static void diffNew(int[][] b, int x1, int y1, int x2, int y2, int k){        b[x1][y1] += k;        b[x1][y2 + 1] -= k;        b[x2 + 1][y1] -=k;        b[x2 + 1][y2 + 1] += k;    }        public static void main(String[] args)throws Exception{        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));        String[] strNums = buf.readLine().split(" ");        int m = Integer.valueOf(strNums[0]);        int n = Integer.valueOf(strNums[1]);        int q = Integer.valueOf(strNums[2]);        int[][] a = new int[m + 2][n + 2];        int[][] b = new int[m + 2][n + 2];        for(int i = 1; i <= m; ++i){            String[] nums = buf.readLine().split(" ");            for(int j = 1; j <= n; ++j){                int k = Integer.valueOf(nums[j - 1]);                diff(b, i, j, k);            }        }        for(int i = 0; i < q; ++i){            String[] nums = buf.readLine().split(" ");            int x1 = Integer.valueOf(nums[0]);            int y1 = Integer.valueOf(nums[1]);            int x2 = Integer.valueOf(nums[2]);            int y2 = Integer.valueOf(nums[3]);            int k = Integer.valueOf(nums[4]);            diffNew(b, x1, y1, x2, y2, k);        }        for(int i = 1; i <= m; ++i){            for(int j = 1; j <= n; ++j){                a[i][j] = a[i][j - 1] + a[i - 1][j] + b[i][j] - a[i - 1][j - 1];                 writer.write(a[i][j] + " ");                // System.out.printf("%d ", a[i][j]);            }            writer.write("\n");            // System.out.println();        }         //所有write下的内容,会先存在writers中,当启用flush以后,会输出存在其中的内容。如果没有调用flush,则不会将writer中的内容进行输出。        writer.flush();        buf.close();        writer.close();    }}

 

上一篇:AcWing 802. 区间和
下一篇:AcWing 797. 差分

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月22日 08时12分59秒