首页 > 编程语言 > 详细

二维前缀和 C++版本 Python版本

时间:2020-01-15 18:11:36      阅读:94      评论:0      收藏:0      [点我收藏+]

AcWing 796 子矩阵的和   https://www.acwing.com/activity/content/problem/content/830/1/

 

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

const int N = 1005;

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-1][j] + s[i][j-1] - s[i-1][j-1] + a[i][j];
        }
    while(q --)
    {
        int x1, y1, x2, y2;
        scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
        int t = s[x2][y2] - s[x2][y1-1] - s[x1-1][y2] + s[x1-1][y1-1];
        printf("%d\n", t);
    }
    return 0;
}

 

n, m, q = map(int, input().split())
a = [[0 for i in range(m+5)] for i in range(n+5)]
b = [[0 for i in range(m+5)] for i in range(n+5)]#前缀和
for i in range(1, n+1):
    row = [0] + list(map(int, input().split()))
    for j in range(1, m+1):
        a[i][j] = row[j]
        b[i][j] = b[i-1][j] + b[i][j-1] - b[i-1][j-1] + a[i][j]

while q:
    q -= 1
    x1, y1, x2, y2 = map(int, input().split())
    res = b[x2][y2] - b[x1-1][y2] - b[x2][y1-1] + b[x1-1][y1-1]
    print(res)

二维前缀和 C++版本 Python版本

原文:https://www.cnblogs.com/Chaosliang/p/12197735.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!