Pseudo Range Minimum Query

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 09:29:23

问题


I have a problem with my assignment which requires me to solve a problem that is similar to range-minimum-query. The problem is roughly described below:

I am supposed to code a java program which reads in large bunch of integers (about 100,000) and store them into some data structure. Then, my program must answer queries for the minimum number in a given range [i,j]. I have successfully devised an algorithm to solve this problem. However, it is just not fast enough.

The pseudo-code for my algorithm is as follows:

// Read all the integers into an ArrayList

// For each query,
// Read in range values [i,j] (note that i and j is "actual index" + 1 in this case)
// Push element at index i-1 into a Stack
// Loop from index i to j-1 in the ArrayList (tracking the current index with variable k)
[Begin loop]       
// If element at k is lesser than the one at the top of the stack, push the element at k into the Stack.
[End of loop]

Could someone please advise me on what I could do so that my algorithm would be fast enough to solve this problem?

The assignment files can be found at this link: http://bit.ly/1bTfFKa

I have been stumped by this problem for days. Any help would be much appreciated. Thanks.


回答1:


Your problem is a static range minimum query (RMQ). Suppose you have N numbers. The simplest algorithm you could use is an algorithm that would create an array of size N and store the numbers, and another one that will be of size sqrtN, and will hold the RMQ of each interval of size sqrtN in the array. This should work since N is not very large, but if you have many queries you may want to use a different algorithm.
That being said, the fastest algorithm you could use is making a Sparse Table out of the numbers, which will allow you to answer the queries in O(1). Constructing the sparse table is O(NlogN) which, given N = 10^5 should be just fine.
Finally, the ultimate RMQ algorithm is using a Segment Tree, which also supports updates (single-element as well as ranges), and it's O(N) to construct the Segment Tree, and O(logN) per query and update. All of these algorithms are very well exposed here. For more information in Segment Trees see these tutorials I wrote myself. link
Good Luck!



来源:https://stackoverflow.com/questions/19376893/pseudo-range-minimum-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!