前缀和
S0 = 0
Si = A1 + A2 + ... + Ai
i
不能为1
作用:求[l,r]
的和 = S[r]-S[l-1]
for(int i = 1; i <= n; i++) cin >> arr[i];
s[0] = 0;
for(int i = 1; i <= n; i++) s[i] = s[i] + arr[i] + s[i-1];
子矩阵的和
输入一个 n 行 m 列的整数矩阵,再输入 q 个询问,每个询问包含四个整数 x1,y1,x2,y2,表示一个子矩阵的左上角坐标和右下角坐标。
对于每个询问输出子矩阵中所有数的和。
输入格式
第一行包含三个整数 n,m,q。
接下来 n 行,每行包含 m 个整数,表示整数矩阵。
接下来 q 行,每行包含四个整数 x1,y1,x2,y2,表示一组询问。
输出格式共 q 行,每行输出一个询问的结果。
数据范围
1≤n,m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤矩阵内元素的值≤1000
输入样例:
3 4 3
1 7 2 4
3 6 2 8
2 1 2 3
1 1 2 2
2 1 3 4
1 3 3 4
输出样例:
17
27
21
求前缀和
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 1000 + 11;
int arr[maxn][maxn];
int n,m,q;
int main(){
cin >> n >> m >> q;
memset(arr,0,sizeof(arr));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++) cin >> arr[i][j];
//先算二分前缀和
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
arr[i][j] = arr[i][j] + arr[i][j-1] + arr[i-1][j] - arr[i-1][j-1];
}
}
//末尾前缀和,减去上面和左边的前缀和,加上多减去的部分
while(q--){
int x1,y1,x2,y2; cin >> x1 >> y1 >> x2 >> y2;
int res = arr[x2][y2] - arr[x1-1][y2] - arr[x2][y1-1] + arr[x1-1][y1-1];
cout << res << endl;
}
return 0;
}
差分
#include <iostream>
using namespace std;
const int N = 1e5 + 11;
int n,m;
int a[N],b[N];
void insert(int l,int r,int c){
b[l] += c;
b[r+1] -= c;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++) insert(i,i,a[i]);
while(m--){
int l,r,c; cin >> l >> r >> c;
insert(l,r,c);
}
for(int i = 1; i <= n; i++) b[i] += b[i-1];
for(int i = 1; i <= n; i++) cout << b[i] << " ";
return 0;
}