当前位置:网站首页>Sum of acwing796 submatrix

Sum of acwing796 submatrix

2022-06-12 16:17:00 _ Liuxiaoyu

Enter a n That's ok m The integer matrix of columns , Input again q A asked , Each query contains four integers x1,y1,x2,y2, Represents the upper left and lower right coordinates of a submatrix .

For each query, the sum of all numbers in the output submatrix .

Input format
The first line contains three integers n,m,q.

Next n That's ok , Each row contains m It's an integer , Represents an integer matrix .

Next q That's ok , Each line contains four integers x1,y1,x2,y2, A group of questions .

Output format
common q That's ok , Output one query result per line .

Data range
1≤n,m≤1000,
1≤q≤200000,
1≤x1≤x2≤n,
1≤y1≤y2≤m,
−1000≤ The values of the elements in the matrix ≤1000

Solution of two-dimensional difference : Subtract the area of two matrices , Then add the area of the repeated subtraction
 Insert picture description here
S(i,j) How to calculate : S(i ,j) = S(i-1, j) + S(i, j - 1) - S(i-1, j -1) + a(i , j)
 Insert picture description here

#include <iostream>
using namespace std;

const int N = 1010;
int a[N][N], s[N][N];
int n,m,q;

int main()
{
    
    cin >> n >> m >> q;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++) 
        {
    
            cin >> a[i][j];
            s[i][j] = s[i-1][j] + s[i][j-1]-s[i-1][j-1] + a[i][j];  //  The prefix and 
        }
        
    while(q--)
    {
    
        int x1,y1,x2,y2;
        cin >> x1 >> y1 >> x2 >> y2;
        int re = s[x2][y2]-s[x1-1][y2] - s[x2][y1-1] + s[x1-1][y1-1];  //  Submatrix and 
        cout << re <<endl;
    }
    return 0;
}
原网站

版权声明
本文为[_ Liuxiaoyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121608188077.html