当前位置:网站首页>二维前缀和
二维前缀和
2022-07-28 09:46:00 【Boletb】
1.预处理
首先要计算左上角坐标为(x1,y1)右下角坐标为(x2,y2)的矩形内数据的和要先进行预处理
目的是为了得出从(1,1)到(i,j)的矩形内数据的和的公式

即sum[ i ][ j ]=sum[ i-1 ][ j ]+sum[ i ][ j-1 ]-sum[ i-1 ][ j-1]+a[ i ][ j ];
2.得公式
经过预处理之后我们就可以进行计算

最后我们得出此矩阵的和为:
sum[ x2 ][ y2 ] - sum[ x2 ][ y1-1 ]-sum[ x1-1 ][ y2 ]+sum[ x1-1 ][ y1-1 ];
注意:因为我们在预处理和最后得出公式的时候,在sum的下标中都有[ x1-1 ]或者[ y1-1 ],所以我们在读取整个矩阵时行列坐标均从1开始而非0。
接下来是一道二维前缀和的入门题目
和我自己做这道题时的代码
#include<stdio.h>
#include<math.h>
#define N 130
int a[N][N];
int sum[N][N];
int max=0,p=0;
int main()
{
int n;
scanf("%d",&n);
int i=0,j=0;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
scanf("%d",&a[i][j]);
sum[i][j]=sum[i-1][j]+sum[i][j-1]-sum[i-1][j-1]+a[i][j];
//这里是预处理,得出sum[i][j]的计算公式。
}
}
int x1,y1,x2,y2;
//这里要用四个变量循环判断坐标。x1和y1是矩形的左上角坐标,x2和y2是矩形的右上角坐标
for(x1=1;x1<n;x1++){
for(y1=1;y1<n;y1++){
for(x2=x1;x2<=n;x2++){
for(y2=y1;y2<=n;y2++){
p=sum[x2][y2]-sum[x2][y1-1]-sum[x1-1][y2]+sum[x1-1][y1-1];
max=(max>p?max:p);
//从这些矩阵和中挑出一个最大值
}
}
}
}
printf("%d",max);
return 0;
}边栏推荐
- LSA and optimization of OSPF
- OSS direct upload rails service practice
- 刚获融资的Espresso Systems,知识产权与团队道德双双陷入困境
- 超级原始人系列盲盒即将上线,PlatoFarm赋能超多权益
- 房地产数字化转型方案:全方位数智化系统运营,助力房企管控实效提升
- 为报复公司解雇,我更改了项目的所有代码注释!
- Which strings will be resolved to null by fastjason?
- Deepin 下安装 LAMP
- 广州地铁14号线新市墟站开建,白云区居民即将开启双线换乘模式!
- (10) Defer keyword
猜你喜欢

二分、三分、01分数规划【第III弹】

这种动态规划你见过吗——状态机动态规划之股票问题(中)

C# 读写文件从用户态切到内核态,到底是个什么流程?

超级原始人系列盲盒即将上线,PlatoFarm赋能超多权益

Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 2)

Installing MySQL for Linux operating system (centos7)

2022-uni-app解析token标准的方式-使用jsrsasign-爬坑过了

Espresso systems, which has just obtained financing, has both intellectual property rights and team ethics in trouble

Plato Farm-以柏拉图为目标的农场元宇宙游戏

Seektiger eco pass STI new progress, log in to ZB on April 14
随机推荐
fastjson中@jsonType注解的功能简介说明
New features of ES6
Seektiger eco pass STI new progress, log in to ZB on April 14
3 minutes to tell you how to become a hacker | zero foundation to hacker getting started guide, you only need to master these five abilities
哪些字符串会被FastJson解析为null呢?
【FPGA教程案例41】图像案例1——通过verilog读取图片
Today, I want to talk about the data types of MySQL database
[ESP32][esp-idf] esp32s3快速搭建LVGLV7.9
PHP7 中 ?? 与? :的区别
Fixedwindowrollingpolicy introduction
[collection] linear algebra let me think - Summary of chapter topics
Experiment 5: user and user group management
The high temperature continues, and public transport enterprises carry out special safety training
DAO社区的胜利,Tiger DAO VC胜在治理与共识
OSPF expansion configuration, routing principles, anti ring and re release
Joint search set
OpenAtom OpenHarmony分论坛,今天14:00见!附大事记精彩发布
LSA and optimization of OSPF
房地产数字化转型方案:全方位数智化系统运营,助力房企管控实效提升
Linux操作系统(Centos7)安装MySQL