RMQ区间最值

//poj 3264 
#include <iostream> //线段树,求区间的最值问题
using namespace std;
struct segment
{
int max,min;
}table[
200000]; //4*50000
int arr[50005],MAX,MIN;
void built_tree(int s,int t,int n)
{
if(s==t)
table[n].max
=table[n].min=arr[s];
else
{
int mid=(s+t)/2;
built_tree(s,mid,
2*n);
built_tree(mid
+1,t,2*n+1);
table[n].max
=max(table[2*n].max,table[2*n+1].max);
table[n].min
=min(table[2*n].min,table[2*n+1].min);
}
}
void range(int s,int t,int n,int head,int end)
{
if(s==head&&t==end)
{
MAX
=max(MAX,table[n].max);
MIN
=min(MIN,table[n].min);
}
else
{
int mid=(head+end)/2; //注意不要写成 int mid=(s+t)/2;
if(s<=mid)
range(s,min(mid,t),
2*n,head,mid);
if(t>mid)
range(max(s,mid
+1),t,2*n+1,mid+1,end);
//这里不用再添加 MAX=max(table[2*n].max,table[2*n+1].max); MIN=min(table[2*n].min,table[2*n+1].min);
//因为执行range(s,min(mid,t),2*n,head,mid);之后,MAX已经是MAX=max(MAX,table[2*n].max);
//同理再执行range(max(s,mid+1),t,2*n+1,mid+1,end); MAX已经是table[2*n].max,table[2*n+1].max 两者的最大值了
}
}
int main()
{
int n,q,s,t;
scanf(
"%d%d",&n,&q);
for(int i=1;i<=n;++i) //下标从1开始
scanf("%d",arr+i);
built_tree(
1,n,1);
while(q--)
{
scanf(
"%d%d",&s,&t);
MAX
=0;MIN=1000001;
range(s,t,
1,1,n);
printf(
"%d\n",MAX-MIN);
}
return 0;
}

  

#include<iostream>        //ST算法(Sparse Table,稀疏表),求区间的最值问题
#include <cmath>
using namespace std;
const int max_n=50005;
int arr[max_n],n,t,l,r;
int rmq_m[max_n][16],rmq_n[max_n][16]; //16>=log2(50000)
void rmq_init()
{
int i,j;
for(i=1;i<=n;++i)
rmq_m[i][
0]=rmq_n[i][0]=arr[i];
for(j=1;j<=log((double)(n+1))/log(2.0);++j) //j表示区间长度为2^j
{
for(i=1;i+(1<<j)-1<=n;++i)
{
rmq_m[i][j]
=max(rmq_m[i][j-1],rmq_m[i+(1<<(j-1))][j-1]);
rmq_n[i][j]
=min(rmq_n[i][j-1],rmq_n[i+(1<<(j-1))][j-1]);
}
}
}
int rmq(int left,int right)
{
int m=(int)(log((double)(right-left+1))/log(2.0));
int a=max(rmq_m[left][m],rmq_m[right-(1<<m)+1][m]);
int b=min(rmq_n[left][m],rmq_n[right-(1<<m)+1][m]);
return a-b;
}
int main()
{
scanf(
"%d%d",&n,&t);
for(int i=1;i<=n;++i)
scanf(
"%d",arr+i);
rmq_init();
while(t--)
{
scanf(
"%d%d",&l,&r);
printf(
"%d\n",rmq(l,r));
}
return 0;
}

  

posted on 2011-08-24 16:03  sysu_mjc  阅读(194)  评论(0编辑  收藏  举报

导航