目录
AcWing 795. 前缀和
输入样例:
5 3
2 1 3 6 4
1 2
1 3
2 4
输出样例:
3
6
10
using namespace std;
const int N = 1e5+10;
int a[N];
int main()
{
int n,m;
cin >> n >> m;
for (int i = 1; i <= n; i ++ ){
scanf("%d", &a[i]);
a[i] += a[i-1];
}
int l,r;
for (int i = 0; i < m; i ++ ){
scanf("%d%d", &l, &r);
cout << a[r]-a[l-1] << endl;
}
return 0;
}
AcWing 796.子矩阵的和
输入样例:
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
using namespace std;
const int N = 1010;
int a[N][N],s[N][N];
int main()
{
int n,m,x;
cin >> n >> m >> x;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ ){
scanf("%d", &a[i][j]);
s[i][j] += s[i-1][j]+s[i][j-1]-s[i-1][j-1]+a[i][j];
}
int x1,x2,y1,y2;
while (x -- )
{
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
cout << s[x2][y2]-s[x2][y1-1]-s[x1-1][y2]+s[x1-1][y1-1] <<endl;
}
return 0;
}
AcWing 797.差分
输入样例:
6 3
1 2 2 1 2 1
1 3 1
3 5 1
1 6 1
输出样例:
3 4 5 3 4 2
using namespace std;
const int N = 1e5+10;
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];
}
int l,r,add;
for (int i = 0; i < m; i ++ ){
scanf("%d%d%d", &l, &r, &add);
b[l] += add;
b[r+1] -= add;
}
for (int i = 1; i <= n; i ++ ){
b[i] += b[i-1];
printf("%d ",b[i]);
}
return 0;
}
AcWing 798.差分矩阵
输入样例:
3 4 3
1 2 2 1
3 2 2 1
1 1 1 1
1 1 2 2 1
1 3 2 3 2
3 1 3 4 1
输出样例:
2 3 4 1
4 3 4 1
2 2 2 2
using namespace std;
const int N = 1010;
int a[N][N],b[N][N];
void change(int x1,int y1,int x2,int y2,int add)
{
b[x1][y1] += add;
b[x1][y2+1] -= add;
b[x2+1][y1] -= add;
b[x2+1][y2+1] += add;
}
int main()
{
int n,m,x;
cin >> n >> m >>x;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ ){
scanf("%d", &a[i][j]);
change(i,j,i,j,a[i][j]);
}
int x1,x2,y1,y2,add;
for (int i = 0; i < x; i ++ ){
scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &add);
change(x1, y1, x2, y2, add);
}
for (int i = 1; i <= n; i ++ ){
for (int j = 1; j <= m; j ++ ){
b[i][j] += b[i-1][j]+b[i][j-1]-b[i-1][j-1];
cout << b[i][j] << ' ';
}
cout << endl;
}
return 0;
}