NYOJ 119 士兵杀敌(三)[RMQ例题]【解题报告】

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iostream>
#define inf 0x3f3f3f3f
#define LL unsigned long long
#define maxn 100001
using namespace std;
int n,q;
int a[maxn];
int maxsum[maxn][20],minsum[maxn][20];

void RMQ(int num)
{
	for(int j=1;j<20;j++)
	{
		for(int i=1;i<=num;i++)
		{
			if(i+(1<<j)-1<=num)
			{
				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]);
			}
		}
	}
}
void query(int l,int r)
{
	int x=log(r-l+1)/log(2);
	int ans1=max(maxsum[l][x],maxsum[r+1-(1<<x)][x]);
	int ans2=min(minsum[l][x],minsum[r+1-(1<<x)][x]);
	printf("%d\n",ans1-ans2); 
}
/******Program Begin*********/
int main()
{
	scanf("%d%d",&n,&q);
	int x,y;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a[i]);
		maxsum[i][0]=minsum[i][0]=a[i];
	}
	RMQ(n);
	for(int i=1;i<=q;i++)
	{
		scanf("%d%d",&x,&y);
		query(x,y);
	}
	return 0;
}
/*******Program End**********/
http://blog.csdn.net/qq_33583069/article/details/51242919关于RMQ问题和ST算法的分析.

你可能感兴趣的:(RMQ,st)