博客
关于我
2020.2.16普及C组 方格纸(square【纪中】【差分】【前缀和】
阅读量:351 次
发布时间:2019-03-04

本文共 1389 字,大约阅读时间需要 4 分钟。

正解:前缀和+二维差分

差分其实就是前缀和的逆运算;

假设有一个数组 a [ 5 ] = 1 , 2 , 3 , 4 , 5 a[5]={1,2,3,4,5} ,它的差分数组 b [ 5 ] = 1 , 1 , 1 , 1 , 1 b[5]={1,1,1,1,1} 。显然,差分数组的每个元素可以通过原数组的相邻元素之差得到,即 b [ i ] = a [ i ] − a [ i − 1 ] b[i]=a[i]-a[i-1] 。因此,我们可以推出,原数组的前缀和等于差分数组的前缀和,这也是为什么说差分就是前缀和的逆运算。

知道了这个,差分还有一个重要的应用:在二维网格中对某个区间进行加数操作,然后问操作后的某个位置的值是多少。这种方法在计算机科学和数据处理领域广泛应用。

二维差分与一维差分的关系

二维差分和一维差分本质上是一样的操作。只不过,我们扩展到了二维网格中。具体来说,对于一个二维网格 x 1 , y 1 , x 2 , y 2 x1,y1,x2,y2 ,我们需要对四个角进行赋值,通常是 1 1 − 1 -1 。赋值完成后,我们通过以下代码来计算最终的网格值:

a[x1][y1]++; a[x2+1][y2+1]++; a[x1][y2+1]--; a[x2+1][y1]--;

这样就能完成二维差分操作啦!

代码实现

#include 
#include
#include
#include
using namespace std;long long f[3500][3500], a[3500][3500];long long n, m, x, y, x1, y1, x2, y2;int main() { freopen("square.in", "r", stdin); freopen("square.out", "w", stdout); scanf("%lld", &n); for (int i = 1; i <= n; i++) { scanf("%lld %lld %lld %lld", &x1, &y1, &x2, &y2); a[x1][y1]++; a[x2+1][y2+1]++; a[x1][y2+1]--; a[x2+1][y1]--; } for (int i = 1; i <= 3000; i++) for (int j = 1; j <= 3000; j++) f[i][j] = f[i-1][j] + f[i][j-1] - f[i-1][j-1] + a[i][j]; cin >> m; for (int i = 1; i <= m; i++) { scanf("%lld %lld", &x, &y); printf("%lld\n", f[x][y]); } return 0;}

通过上述代码,我们可以轻松完成二维差分操作,并输出最终的网格值。如果你对具体实现细节感兴趣,可以继续深入研究。

转载地址:http://bjle.baihongyu.com/

你可能感兴趣的文章
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
order by rand()
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>