[USACO07JAN]平衡的阵容Balanced Lineup RMQ模板题

Code:

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 50000 + 12;
int A[maxn];
int dmax[maxn][40];
int dmin[maxn][40];
void init(int *A, int n){
	for (int i = 1; i <= n; ++i)
		dmin[i][0] = dmax[i][0] = A[i];
	for(int j=1;(1<<j)<=n;++j)
		for (int i = 1; i + (1 << j) - 1 <= n; ++i)
		{
			dmin[i][j] = min(dmin[i][j-1], dmin[i + (1 << (j - 1))][j - 1]);
			dmax[i][j] = max(dmax[i][j-1], dmax[i + (1 << (j - 1))][j - 1]);
		}
}
int RMQ(int L, int R){
	int k = 0;
	while (L + (1 << (k + 1)) - 1 <= R)++k;
	int big = max(dmax[L][k], dmax[R - (1 << k)+1][k]);
	int small = min(dmin[L][k], dmin[R - (1 << k) + 1][k]);
	return big - small;
}
int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; ++i) scanf("%d", &A[i]);
	init(A, n);
	for (int i = 1; i <= m; ++i)
	{
		int L, R;
		scanf("%d%d", &L, &R);
		printf("%d\n", RMQ(L, R));
	}
	return 0;
}

  

posted @ 2018-11-09 19:37  EM-LGH  阅读(146)  评论(0编辑  收藏  举报