796. 子矩阵的和(二维前缀和)

题目:

796. 子矩阵的和 - AcWing题库

思路:

1.暴力搜索(搜索时间复杂度为O(n2),很多时候会超时)

  1. 前缀和(左上角(二维)前缀和):本题特殊在不是直接求前n个数的和,而是求矩阵中某个元素左上角所以数的和(包括该元素自己),利用左上角前缀和的运算求子矩阵和。

3.在求左上角前缀和以及由左上角前缀和求子矩阵的过程中都需要运用到容斥原理!!!

代码:

cpp 复制代码
#include<iostream>
#include<cstdio>
using namespace std;
typedef unsigned long long ull;
const int N = 1010;
int n, m, q;
ull a[N][N], s[N][N];//a存储数据,s存储左上前缀和
int main()
{
    cin >> n >> m >> q;
    for (int i = 1; i <= n; i++)//入读数据
        for (int j = 1; j <= m; j++)
            scanf("%d", &a[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] + a[i][j];//容斥原理
    while (q--) {
        ull x1, y1, x2, y2;
        scanf("%llu%llu%llu%llu", &x1, &y1, &x2, &y2);
        printf("%lld\n", s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1]);//容斥原理
    }
}
相关推荐
程序员AlbertTu10 小时前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
Lazionr10 小时前
多态:从多种形态到运行时绑定
开发语言·c++
tryxr11 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_311 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
别动我齐刘海11 小时前
ROS2 Jazzy + C++ 实战路线——ros2_control
c++·人工智能·python·opencv·机器学习·机器人·github
Selvaggia11 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z11 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.11 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
码匠许师傅11 小时前
【C++三方组件】glog:Google 出品的 C++ 日志库
c++
Lazionr11 小时前
二叉搜索树:从树形结构到高效查找
开发语言·c++