简体   繁体   English

计算数组矩形区域中的值之和

[英]compute sum of value in an rectangle area of array

I have a very big array of many value and store it in an row-major 1d array . 我有很多有价值的很大的数组,并将其存储row-major 1d array

ex:  
   1 2 3  
   4 5 6

will be store in int* array = {1,2,3,4,5,6}; 将存储在int* array = {1,2,3,4,5,6};

what I have to do is given the row1, row2, column1, column2 , then print out the area's sum, and it will request to caulate different area for many times. 给我要做的就是给row1, row2, column1, column2 ,然后打印出该区域的总和, 它将要求多次计算不同的区域。

what I have think about it is first use nested loop to traverse the array and store each row's sum in sum_row and store each column's sum in sum_column and store the total element's sum im totalSum . 我对此的想法是,首先使用嵌套循环遍历数组,并将每一行的总和存储在sum_row ,将每一列的总和存储在sum_column然后存储总元素的总和im totalSum

Then totalSum - the row and the columns that surrond it + the elemnts that has been minus twice . 然后totalSum - the row and the columns that surrond it + the elemnts that has been minus twice

But it seems fast enough, is there any algorithm that can do faster or some coding style tips that can make the factor little? 但是似乎足够快,是否有任何算法可以做得更快,或者是否有一些编码风格的技巧可以使系数变小?

Thx in advance. 提前谢谢。

It seems to me that you have replaced one double iteration with another. 在我看来,您已经用另一个替换了一个双重迭代。 The problem is in subtracting " the elemnts that has been minus twice "; 问题在于减去“ the elemnts that has been minus twice ”。 unless I'm mistaken, this involves iterating over those elements to sum them. 除非我弄错了,否则这涉及迭代这些元素以求和。

Instead, just iterate over the rectangular area that you need to sum. 相反,只需遍历需要求和的矩形区域即可。 I doubt it will be any slower. 我怀疑会不会更慢。

A more efficient algorithm can be obtained by generating the matrix of summed upper-left matrices. 通过生成求和的左上矩阵矩阵,可以获得更有效的算法。 (See the Wikipedia article on summed area table .) You can then compute any submatrix sum by looking up four area sums. (请参阅Wikipedia关于总面积表的文章。)然后,您可以通过查找四个面积总和来计算任何子矩阵总和。

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

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