简体   繁体   English

如何有效地查找网格中某个范围内的元素总数?

[英]How to find sum of elements in a range in a grid efficiently?

Given a n by n grid of positive numbers, what is the best complexity that can be achieved for obtaining the sum of elements in a range described by the corners of rectangle of area considered given as (x1,y1) and (x2,y2) ? 给定一个nn的正数网格,要获得由以(x1,y1)(x2,y2)给出的面积矩形的角所描述的范围内的元素总和,可以实现的最佳复杂度是什么? ? There will be q such queries. 将有q这样的查询。

PS: Considering the naive solution, the complexity is O(q*n^2) . PS:考虑到天真的解决方案,复杂度为O(q*n^2)

Suppose you sum along the rows as in m69's comment to produce a matrix where every element is the sum of the corresponding element in the original matrix and all elements to the left of it. 假设您按照m69的注释沿行求和以生成一个矩阵,其中每个元素都是原始矩阵中相应元素及其左侧所有元素的总和。 Then you do the same thing summing down the columns of that matrix of sums and you get a matrix where every element is the sum of a rectangular sub-array of elements to its left and above it. 然后,您可以对总和矩阵的各列进行总和,然后得到一个矩阵,其中每个元素都是元素左侧和上方的矩形子数组的和。

Now take four points in this array of sums: 现在,在此求和数组中取四点:

AB AB

CD 光盘

The value D - B - C + A contains the sum of a rectangular region with one corner at D and the other corners just to D's side of A, B, and C, as you can see by working out how many times points in the various regions are added and subtracted. 值D-B-C + A包含一个矩形区域的总和,该矩形区域的一个角位于D处,而另一个角仅位于D的A,B和C侧,如您所得出的,可以计算出各个区域相加和相减。 So after O(n^2) pre-processing you can answer queries in time O(1) 因此,在O(n ^ 2)预处理之后,您可以在O(1)时间内回答查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM