题意:
求区间最大最小值之差,上线段树。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
const int MAXN=50000+7;
int t[MAXN<<2],MIN[MAXN<<2],MAX[MAXN<<2],a[MAXN];
void build(int root,int l,int r)
{
if(l==r)
MIN[root]=MAX[root]=a[l];
else
{
int mid=(l+r)/2;
build(lson);
build(rson);
MIN[root]=min(MIN[root<<1],MIN[root<<1|1]);
MAX[root]=max(MAX[root<<1],MAX[root<<1|1]);
}
}
int queryMAX(int root,int l,int r,int L,int R)
{
if(r<L||l>R)
return 0;
if(L<=l&&r<=R)
return MAX[root];
int mid=(l+r)/2;
int x=max(queryMAX(lson,L,R),queryMAX(rson,L,R));
return x;
}
int queryMIN(int root,int l,int r,int L,int R)
{
if(r<L||l>R)
return 1000005;
if(L<=l&&r<=R)
return MIN[root];
int mid=(l+r)/2;
int x=min(queryMIN(lson,L,R),queryMIN(rson,L,R));
return x;
}
void debug(int root,int l,int r)
{
if(l==r){
printf("%d:%d~%d %d %d\n",root,l,r,MAX[root],MIN[root]);
return ;}
else
printf("%d:%d~%d %d %d\n",root,l,r,MAX[root],MIN[root]);
int mid=(l+r)/2;
debug(root*2,l,mid);
debug(root*2+1,mid+1,r);
}
int main()
{
int n,m,i;
while(~scanf("%d%d",&n,&m))
{
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
// debug(1,1,n);
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
// printf("%d %d\n",queryMAX(1,1,n,x,y),queryMIN(1,1,n,x,y));
printf("%d\n",queryMAX(1,1,n,x,y)-queryMIN(1,1,n,x,y));
}
}
}
本文介绍了一种使用线段树解决区间查询问题的方法,即快速计算任意区间内的最大值和最小值,并通过两者之差得出结果。适用于需要频繁进行区间查询的应用场景。
467

被折叠的 条评论
为什么被折叠?



