Range Minimum Query

Range Minimum Query is used on arrays to find the position of an element with the minimum value between two specified indices. This problem can be solved in many different ways, such as dynamic programming, segment tree, ect. Here shows the C++ implementation of so-called sparse table algorithm.

 

#include <cmath> #include <fstream> #include <iomanip> #include <iostream> using namespace std; int intArray[] = { 2, 4, 3, 1, 6, 7, 8, 9, 1, 7, }; int size = sizeof(intArray) / sizeof(int); int sparseTableSearch(int *intArray, int size, int left, int right); int main() { ofstream outfile; outfile.open("table.txt"); if(!outfile) { cerr << "can not open input file." << endl; return -1; } for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { if(i <= j) outfile << setw(2) << sparseTableSearch(intArray, size, i, j); else outfile << setw(2) << " "; } outfile << endl; } outfile << endl; outfile.close(); return 0; } int sparseTableSearch(int *intArray, int size, int left, int right) { static bool first = true; static int **table = new int*[size]; if(first) { int N = (int)(log((double)size) / log(2.0)); for(int i = 0; i < size; ++i) { table[i] = new int[N]; table[i][0] = i; } for(int j = 1; j <= N; ++j) { for(int i = 0; i + (1 << j) - 1 < size ; ++i) { if(intArray[table[i][j - 1]] < intArray[table[i + (1 << (j - 1))][j - 1]]) table[i][j] = table[i][j - 1]; else table[i][j] = table[i + (1 << (j - 1))][j - 1]; } } first = false; } int k = (int)(log(double(right - left + 1)) / log(2.0)); if(intArray[table[left][k]] < intArray[table[right - (1 << k) + 1][k]]) return table[left][k]; else return table[right - (1 << k) + 1][k]; }

The file output:

0 0 0 3 3 3 3 3 8 8 1 2 3 3 3 3 3 8 8 2 3 3 3 3 3 8 8 3 3 3 3 3 8 8 4 4 4 4 8 8 5 5 5 8 8 6 6 8 8 7 8 8 8 8 9

你可能感兴趣的:(tree,table,Arrays,query,input,output)