一维前缀和
https://www.acwing.com/problem/content/description/797/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e5 + 15;
int n, k, a;
int s[N];
int main() {
cin >> n >> k;
//预处理前缀和
for(int i = 1; i <= n; i++) {
cin >> a;
s[i] = s[i - 1] + a;
}
while(k--) {
int l, r;
cin >> l >> r;
cout << s[r] - s[l - 1] << endl;
}
return 0;
}
二维前缀和
https://www.acwing.com/problem/content/798/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e3 + 15;
int n, m, q, k;
int s[N][N];
int main() {
cin >> n >> m >> q;
//预处理前缀和
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> k;
s[i][j] = k + s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
}
}
while(q--) {
int x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1] << endl;
}
return 0;
}
一维差分
https://www.acwing.com/problem/content/799/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e5 + 15;
int n, m;
int a[N], b[N];
int main() {
cin >> n >> m;
for(int i = 1; i <= n; i++) {
cin >> a[i];
b[i] = a[i] - a[i - 1];
}
while(m--) {
int l, r, c;
cin >> l >> r >> c;
b[l] += c;
b[r + 1] -= c;
}
for(int i = 1; i <= n; i++) {
b[i] += b[i - 1];
cout << b[i] << " ";
}
return 0;
}
二维差分
https://www.acwing.com/problem/content/description/800/
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1e3 + 15;
int n, m, q;
int a[N][N], b[N][N];
int main() {
cin >> n >> m >> q;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
cin >> a[i][j];
b[i][j] = a[i][j] - a[i - 1][j] - a[i][j - 1] + a[i - 1][j - 1];
}
}
while(q--) {
int x1, y1, x2, y2, x;
cin >> x1 >> y1 >> x2 >> y2 >> x;
b[x1][y1] += x;
b[x2 + 1][y1] -= x;
b[x1][y2 + 1] -= x;
b[x2 + 1][y2 + 1] += x;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
a[i][j] = b[i][j] + a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1];
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}