C++ sum of sub-matrices (two-dimensional prefix sum)

Enter an integer matrix with n rows and m columns, and then enter q queries. Each query contains four integers x1, y1, x2, y2, which represent the coordinates of the upper left corner and the lower right corner of a sub-matrix.
For each query, output the sum of all numbers in the sub-matrix.
Input format The
first line contains three integers n, m, q.
The next n rows, each row contains m integers, representing a matrix of integers.
Next line q, each line contains four integers x1, y1, x2, y2, representing a set of queries.
Output format There are
q lines in total, and each line outputs one query result.
Data range
1≤n,m≤1000,1≤q≤200000,
1≤x1≤x2≤n,1≤y1≤y2≤m,
−1000≤value of elements in matrix≤1000
Input example:
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
Output example:
17
27
21

AC code:

#include<stdio.h>

int a[1010][1010];
int n,m,q;

int main()//坐标系:行号对应x坐标,列号对应y坐标
{
    
    
    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]);//加了两次要抵消掉一次
            a[i][j]+=a[i-1][j]+a[i][j-1]-a[i-1][j-1];
        }
    }
    int x1,y1,x2,y2;
    while(q--)
    {
    
    
        scanf("%d%d%d%d",&x1,&y1,&x2,&y2);//减了两次要抵消掉一次
        printf("%d\n",a[x2][y2]-a[x2][y1-1]-a[x1-1][y2]+a[x1-1][y1-1]);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108783592