问题描述:
找出数组A[],任意区间[i,j]的最小值
/* RMQ问题 区间最值查询 */ #include <iostream> using namespace std; #define MAX 100 //方法1 //M[i][j]表示区间i,j最值的索引 //构造M复杂度O(n^2) void RMQ1(int M[][MAX],int A[],int N){ int i, j; for (i =0; i < N; i++) M[i][i] = i; for (i = 0; i < N; i++) for (j = i + 1; j < N; j++) //若前者小于后者,则把后者的索引值付给M[i][j] if (A[M[i][j - 1]] < A[j]) M[i][j] = M[i][j - 1]; //否则前者的索引值付给M[i][j] else M[i][j] = j; } /* 方法2: ST算法 M[ i ][ j ] 是以i 开始,长度为 2^j 的子数组的最小值的索引 分两个区间,M[i][j]为这两个区间最值的索引 则M[i][j]={M[i][j-1],M[i+2^(j-1)+1][j-1]} 构造M时间复杂度O(nlogn) 如何求区间的最值RMQ[i][j]? 设k=log(j-i+1) RMQ[i][j]={M[i][k],M[j-2^k+1][k]} 时间复杂度O(1) */ void RMQ2(int M[][MAX], int A[], int N) { int i, j; //initialize M for the intervals with length 1 for (i = 0; i < N; i++) M[i][0] = i; //compute values from smaller to bigger intervals for (j = 1; 1 << j <= N; j++) for (i = 0; i + (1 << j) - 1 < N; i++) if (A[M[i][j - 1]] < A[M[i + (1 << (j - 1))][j - 1]]) M[i][j] = M[i][j - 1]; else M[i][j] = M[i + (1 << (j - 1))][j - 1]; } /* 方法3: 线段树 这里M[i]保存结点i区间最小值的位置。初始时M的所有元素为-1 构造M,O(N) 查询O(logn) */ void initialize(int node, int b, int e, int M[], int A[]) { if (b == e){ M[node] = b; return; } //compute the values in the left and right subtrees initialize(2 * node, b, (b + e) / 2, M, A); initialize(2 * node + 1, (b + e) / 2 + 1, e, M, A); //search for the minimum value in the first and //second half of the interval if (A[M[2 * node]] <= A[M[2 * node + 1]]) M[node] = M[2 * node]; else M[node] = M[2 * node + 1]; } int query(int node, int b, int e, int M[], int A[], int i, int j) { int p1, p2; //if the current interval doesn't intersect //the query interval return -1 if (i > e || j < b) return -1; //if the current interval is included in //the query interval return M[node] if (b >= i && e <= j) return M[node]; //compute the minimum position in the //left and right part of the interval p1 = query(2 * node, b, (b + e) / 2, M, A, i, j); p2 = query(2 * node + 1, (b + e) / 2 + 1, e, M, A, i, j); //return the position where the overall //minimum is if (p1 == -1) return M[node] = p2; if (p2 == -1) return M[node] = p1; if (A[p1] <= A[p2]) return M[node] = p1; return M[node] = p2; } int main() { int A[]={1,2,3,4,5,6,7,8,9,0}; int M[MAX][MAX]; //ST算法测试 RMQ2(M,A,10); int k=log(9+1); cout<<k<<endl; cout<<A[M[0][k]]<<endl; cout<<A[M[9-(1<<k)+1][k]]<<endl; //end //线段树测试 int N[MAX]; memset(N,-1,sizeof(N));//初始化数组为-1 initialize(1,0,10-1,N,A); int index=query(1,0,9,N,A,1,8); cout<<A[index]<<endl; return 0; }