nyist 119 RMQ

RMQ:

http://blog.csdn.net/liang5630/article/details/7917702

 

#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
const int N=100005;
int minsum[N][21],maxsum[N][21];
// f(i,j)表示i~i+(2^j)-1中最大或者最小值;
//f(i,j)=max(f(i,j-1),f(i+2^(j-1),j-1) 
void RMQ(int n)
{
	for(int j=1;j<=20;j++)
	for(int i=1;i<=n;i++)
	{   if(i+(1<<(j-1))<=n)
		{ maxsum[i][j]=max(maxsum[i][j-1],maxsum[i+(1<<(j-1))][j-1]);
		  minsum[i][j]=min(minsum[i][j-1],minsum[i+(1<<(j-1))][j-1]);
		}
	}
}
int main()
{
	int n,m,i,j,k,maxans,minans;
	cin>>n>>m;
	for(i=1;i<=n;i++)
	{
		scanf("%d",&maxsum[i][0]);
		minsum[i][0]=maxsum[i][0];
	}
	RMQ(n);
	while(m--)
	{
		scanf("%d%d",&i,&j);
		//我们可以取k=log2( j - i + 1),则有:
		//i~j的最大值=max{F[i , k], F[ j - 2 ^ k + 1, k]}。
		k=log10(j-i+1.0)/log10(2.0);
		maxans=max(maxsum[i][k],maxsum[j-(1<<k)+1][k]);
		minans=min(minsum[i][k],minsum[j-(1<<k)+1][k]);
		printf("%d\n",maxans-minans);
	}
	return 0;
}


 

你可能感兴趣的:(nyist 119 RMQ)