前缀和
一维前缀和
#include <iostream>
using namespace std;
const int N = 1e6;
int n,m;
int a[N],s[N];
int main()
{
cin >> n >> m;
for(int i=1;i<=n;i++){
cin >> a[i];
s[i] = s[i-1]+a[i];
}
while(m--){
int l,r;
cin >> l >> r;
cout << s[r] - s[l-1] << endl;
}
return 0;
}
二维前缀和
#include <iostream>
using namespace std;
const int N = 1010;
int n,m,q;
int a[N][N];
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 >> a[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int sum1 = 0;
int sum2 = 0;
for(int p=1;p<=j;p++) sum1 += a[i][p];
for(int p=1;p<=i;p++) sum2 += a[p][j];
s[i][j] = s[i-1][j-1] + sum1 + sum2 - a[i][j];
}
}
while(q--){
int x1,y1,x2,y2;
cin >> x1 >> y1 >> x2 >> y2;
cout << s[x2][y2] - s[x2][y1-1] - s[x1-1][y2] + s[x1-1][y1-1]<<endl;
}
return 0;
}
优化一下
#include <iostream>
using namespace std;
const int N = 1010;
int n, m, q;
int s[N][N];
int main()
{
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
scanf("%d", &s[i][j]);
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1];
while (q -- )
{
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
printf("%d\n", s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
}
return 0;
}
差分
#include <iostream>
using namespace std;
const int N = 100010;
int n, m;
int a[N], b[N];
//b[N]为差分数组,满足a[i] = b[1]+b[2]+...+b[i]
//当b[i]+c时,a[i],a[i+1],...都会变成a[i]+c,a[i+1]+c,...
//所以为了让[i,k]这个范围的a[i]变变成a[i]+c
//需要再令b[k+1]变成b[k+1]-c.这样就只有[i,k]范围内的a[i]变为a[i]+c了
void insert(int l, int r, int c)
{
b[l] += c;
b[r + 1] -= c;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
//因为a[i] = b[1]+b[2]+...+b[i]
for (int i = 1; i <= n; i ++ ) insert(i, i, a[i]);
while (m -- )
{
int l, r, c;
scanf("%d%d%d", &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 ++ ) printf("%d ", b[i]);
return 0;
}