POJ 3264 Balanced Lineup (RMQ)

题目链接:http://poj.org/problem?id=3264

题目大意:

给出n个数, m个询问

求每次询问范围内最大值与最小值得差

方法:

RMQ查询, 其实有点像DP

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
const int maxn = 50010;
int A[maxn];
int Max[maxn][17], Min[maxn][17];

void RMQ(int n)
{
	int k = (int )(log(n) / log(2));
	for(int j=1; j<=k; j++)
		for(int i=1; i<=n; i++)
			if(i + (1<<j) - 1 <= n){
				Max[i][j] = max(Max[i][j-1], Max[i+(1<<(j-1))][j-1]);
				Min[i][j] = min(Min[i][j-1], Min[i+(1<<(j-1))][j-1]);
			}
}

int main()
{
	int n, q;
	while(~scanf("%d%d",&n, &q))
	{
		for(int i=1; i<=n ;i++){
			scanf("%d", &A[i]);
			Max[i][0] = Min[i][0] = A[i];
		}
		RMQ(n);
		
		while(q--){
			int a, b;
			scanf("%d%d",&a, &b);
			int k = (int )(log(b-a+1)/log(2));
			printf("%d\n", max(Max[a][k], Max[b-(1<<k)+1][k]) - min(Min[a][k], Min[b-(1<<k)+1][k]));
			
		}
	}
	return 0;
}


你可能感兴趣的:(POJ 3264 Balanced Lineup (RMQ))