14.差分矩陣


 

 二維差分

原數組a[i][j]

差分數組b[i][j]

使得a數組是b數組的前綴和

同樣開始時假定a[i][j]和b[i][j]都等於0

然后對於a數組中的每一個數再插一遍就好了

一維差分是對一段加上一個值

二維差分是對一個子矩陣加上一個值

b[x1][y1]加上c就是x1,y1右下角的所有點加上c

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 1010;
 4 int a[N][N], b[N][N];
 5 //a是原矩陣
 6 //b是差分矩陣 
 7 void insert(int x1, int y1, int x2, int y2, int c) {
 8     b[x1][y1] += c;
 9     b[x2 + 1][y1] -= c;
10     b[x1][y2 + 1] -= c;
11     b[x2 + 1][y2 + 1] += c;
12 }
13 int main() {
14     int n, m, q;
15     cin >> n >> m >> q;
16     for (int i = 1; i <= n; i++) {
17         for (int j = 1; j <= m; j++) {
18             cin >> a[i][j];
19             insert(i, j, i, j, a[i][j]);
20         }
21     }
22     while (q--) {
23         int x1, y1, x2, y2, c;
24         cin >> x1 >> y1 >> x2 >> y2 >> c;
25         insert(x1, y1, x2, y2, c);
26     }
27     for (int i = 1; i <= n; i++) {
28         for (int j = 1; j <= m; j++) {
29             b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
30             cout << b[i][j] << " ";
31         }
32         cout << endl;
33     }
34     return 0;
35 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM