RMQ range of most value problem

Today, school brother live lectures in the group, told RMQ, before goof off too much on this topic did not see what it is , and then went to scrape together lively.

RMQ (Range Minimum / Maximum Query) issues refer to: the length n of the number of columns A, answering a number of interrogation RMQ (A, i, j) (i, j <= n), returns the number of column A subscripts i, j in the minimum (large) value, that is, RMQ problem is one that find the most value range.

For that matter, most value range, multiple queries, my first reaction was that tree line, it really is the most basic model tree line value problem, other segment tree blog articles there, do not come here alone here.

School brother talk about this topic, talked about the violence method 3, dynamic programming, ST (Sparse Table)

Violence: nothing to say

RMQ you (you A [], you mi, you're not) {
	you rt_max = -INF, rt_min = INF;
	for(int i=mi; i<=ma; i++) {
		rt_max = max(A[i], rt_max);
		rt_min = min (A [i], rt_min);
	}
	return {...};
}

Dynamic Programming:

DP [i] [j] from i to j maintain maximum or minimum value, i.e., state transition equation:

dp[i][j]=max(dp[i][j-1],dp[j][j]);

Thus at the beginning of all the values ​​of all pretreated, as long as the value of each query query dp [i] [j], and can be obtained directly A [i] -A [j] of the maximum and minimum values:

int dp[MX][MX];
void init_RMQ(int A[], int n) {
	for(int i = 0; i < n; i++) {
		dp[i][i] = A[i];
	}
	for(int i = 0; i < n; i++) {
		for(int j = i + 1; j < n; j++) {
			dp[i][j] = max(dp[i][j-1], dp[j][j]);
		}
	}
}

ST algorithm:

This is a binary optimized using DP, dp [i] [j] from the start to the i i 2 ^ j-1 + the value of the most

dp[i][0] = max(A[i] to A[i + (2^j) - 1]) ...A[i]			len = 2^0 = 1 
dp[i][1] = max(A[i] to A[i + (2^j) - 1]) ...A[i],A[i+1];   		len = 2^1 = 2
dp[i][2] = max(A[i] to A[i + (2^j) - 1]) ...A[i],A[i+1],A[i+2],A[i+3]  	len = 2^2 = 4
dp[i][3] = .... len = 2^3 = 8 ...

 

dp [i] [j] is the state transition equation as follows

dp[i][j] = max(dp[i][j - 1], dp[i + 2^(j-1)][j - 1]);
void init_RMQ(int A[], int n) {
	for(int i = 1; i <= n; i++) {
		dp[i][0] = A[i];
	}
	for(int j = 1; (1<<j) <= n; j++) {
		for(int i = 1; (i + (1<<j) - 1) <= n; i++) {
			dp[i][j] = max(dp[i][j-1], dp[i + (1<<(j-1))][j-1]);
		}
	}
}

When we need, A [1] -A [7], the length of the query is 7, we can query the two sections of length 4 to determine the best value for this interval, but log2 (4) = 2

Dp was converted to need, only dp [1] [2] and dp [7-4 + 1] [2] of the two maximum value comparison can be: max (dp [1] [2], dp [4 ][2])

int Query_max(int l,int r) {
	int k= log2(r - l + 1);
	return ( max(dp[l][k], dp[r - (1<<k) + 1][k]));
}

  

Guess you like

Origin www.cnblogs.com/HDMaxfun/p/12189945.html