题目:
输入一个 n 行 m 列的整数矩阵,再输入 q 个询问,每个询问包含四个整数 x2,y2,表示一个子矩阵的左上角坐标和右下角坐标。
对于每个询问输出子矩阵中所有数的和。
输入格式
第一行包含三个整数 n,m,q。
接下来 n 行,每行包含 m 个整数,表示整数矩阵。
接下来 q 行,每行包含四个整数 x1,y1,x2,y2,表示一组询问。
输出格式
共 q 行,每行输出一个询问的结果。
数据范围
≤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>
using namespace std;
const int N = 1010;
int arr[N][N];
int sum[N][N];
int n,m,q;
int main()
{
cin >> n>>m>>q;
// for(int i = 0;i<n;i++)
for(int i = 1;i<=n;i++)
{
// for(int j=0;j<m;j++)
for(int j=1;j<=m;j++)
{
cin>>arr[i][j];
}
}
// for(int i = 0;i<n;i++)
for(int i = 1;i<=n;i++)
{
// for(int j=0;j<m;j++)
for(int j=1;j<=m;j++)
{
// if(j==0)
// {
// sum[i][j] = arr[i][j];
// }else{
sum[i][j] = sum[i][j-1] + arr[i][j];
// }
}
}
while(q--)
{
int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
int res = 0;
for(int i = x1;i <= x2;i++)
{
res+=(sum[i][y2]-sum[i][y1-1]);
}
cout << res<<endl;
}
return 0;
}
反思:
-
数组下标i从1开始计算,方便取数,而且计算 l-r 的数的和时是Sr-S(l-1),避免访问sum[i][-1]。
-
还是超时。
Y总的代码:
#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;
}
作者:yxc
链接:https://www.acwing.com/activity/content/code/content/39797/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
学习:
- S[i][j]的求法:s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1];
- 前缀和的求法:s[x2][y2] - s[x2][y1-1] -s[x1-1][y2] + s[x1-1][y1-1];

1057

被折叠的 条评论
为什么被折叠?



