Acwing 795.前缀和
#include <iostream>
//前缀和
using namespace std;
const int N = 100010;
int a[N],s[N];
int main ()
{
int n,m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
scanf("%d",&a[i]);
s[i]=s[i-1]+a[i];
}
while(m--)
{
int l,r;
cin >> l >> r;
cout << s[r]-s[l-1];
}
return 0;
}
Acwing 796.子矩阵的和
#include <iostream>
using namespace std;
// 子矩阵的和
const int N = 1010;
int a[N][N], s[N][N];
int main()
{
int n, m, q;
scanf("%d%d%d",&n,&m,&q);
for(int i = 1;i <= n; i++)
{
for(int j = 1;j <= m; j++)
{
scanf("%d",&a[i][j]);
s[i][j] = s[i][j-1] + s[i-1][j] - s[i-1][j-1] + a[i][j];
}
}
while (q--)
{
int x_1,y_1,x_2,y_2;
cin >> x_1 >> y_1 >> x_2 >> y_2;
int sum = s[x_2][y_2] - s[x_1-1][y_2] - s[x_2][y_1-1] + s[x_1-1][y_1-1];
printf("%d\n",sum);
}
return 0;
}
Acwing 797.差分
#include <iostream>
using namespace std;
const int N = 100010;//差分
int a[N],b[N];
int main()
{
int n,m;
cin >> n >> m;
for(int i = 1;i <= n;i++)
{
scanf("%d",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++)
{
a[i] = a[i-1] + b[i];
printf("%d ",a[i]);
}
return 0;
}
Acwing 798.差分矩阵
//差分矩阵
#include <iostream>
using namespace std;
const int N = 1010;
int a[N][N],b[N][N];
int main()
{
int n,m,q;
scanf("%d%d%d",&n,&m,&q);
for (int i = 1;i <=n ; i++)
{
for (int j = 1; j <= m; j++)
{
scanf("%d",&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,c;
scanf("%d%d%d%d%d",&x1,&y1,&x2,&y2,&c);
b[x1][y1] += c;
b[x1][y2+1] -= c;
b[x2+1][y1] -= c;
b[x2+1][y2+1] += c;
}
for (int i = 1;i <=n ; i++)
{
for (int j = 1; j <= m; j++)
{
a[i][j] = a[i-1][j] + a[i][j-1] - a[i-1][j-1] + b[i][j];
printf("%d ",a[i][j]);
}
cout << endl;
}
return 0;
}