矩阵的差分
insert函数结合矩阵加对后续元素的影响不难写出。
最后求和的时候,考虑到每次对b[i][j]的影响包含了其本身,只需加等于前面元素带来的影响。
1 #include <iostream> 2 using namespace std; 3 4 const int maxn = 2e3 + 10; 5 int a[maxn][maxn], b[maxn][maxn], n, m, q, i, j, k, l, c; 6 7 void insert(int i, int j, int k, int l, int c) { 8 b[i][j] += c; 9 b[k + 1][j] -= c; 10 b[i][l + 1] -= c; 11 b[k + 1][l + 1] += c; 12 } 13 14 int main() { 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], insert(i, j, i, j, a[i][j]); 19 while (q--) { 20 cin >> i >> j >> k >> l >> c; 21 insert(i, j, k, l, c); 22 } 23 for (int i = 1; i <= n; i++) 24 for (int j = 1; j <= m; j++) 25 b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1]; 26 for (int i = 1; i <= n; i++) { 27 for (int j = 1; j <= m; j++) cout << b[i][j] << " "; 28 cout << '\n'; 29 } 30 return 0; 31 }