#include <iostream>
#include<stdio.h>
using namespace std;
const int maxn=50000+5;
int n,q;
int height[maxn];
struct segtree
{
int left,right;
int maxx,minn;
};
segtree tree[maxn*4];
#include<stdio.h>
using namespace std;
const int maxn=50000+5;
int n,q;
int height[maxn];
struct segtree
{
int left,right;
int maxx,minn;
};
segtree tree[maxn*4];
void build(int low,int high,int index)
{
tree[index].left=low;
tree[index].right=high;
if(low==high)
{
tree[index].maxx=height[low];
tree[index].minn=height[low];
return;
}
else
{
int mid=(low+high)/2;
build(low,mid,index*2);
build(mid+1,high,index*2+1);
tree[index].maxx=max(tree[index*2].maxx,tree[index*2+1].maxx);
tree[index].minn=min(tree[index*2].minn,tree[index*2+1].minn);
}
}
{
tree[index].left=low;
tree[index].right=high;
if(low==high)
{
tree[index].maxx=height[low];
tree[index].minn=height[low];
return;
}
else
{
int mid=(low+high)/2;
build(low,mid,index*2);
build(mid+1,high,index*2+1);
tree[index].maxx=max(tree[index*2].maxx,tree[index*2+1].maxx);
tree[index].minn=min(tree[index*2].minn,tree[index*2+1].minn);
}
}
int qmax(int low,int high,int index)
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].maxx;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmax(low,high,index*2);
}
else if(low>mid)
{
return qmax(low,high,index*2+1);
}
else
{
return max(qmax(low,mid,index*2),qmax(mid+1,high,index*2+1));
}
}
}
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].maxx;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmax(low,high,index*2);
}
else if(low>mid)
{
return qmax(low,high,index*2+1);
}
else
{
return max(qmax(low,mid,index*2),qmax(mid+1,high,index*2+1));
}
}
}
int qmin(int low,int high,int index)
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].minn;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmin(low,high,index*2);
}
else if(low>mid)
{
return qmin(low,high,index*2+1);
}
else
{
return min(qmin(low,mid,index*2),qmin(mid+1,high,index*2+1));
}
}
}
{
if(tree[index].left==low&&tree[index].right==high)
{
return tree[index].minn;
}
else
{
int mid=(tree[index].left+tree[index].right)/2;
if(high<=mid)
{
return qmin(low,high,index*2);
}
else if(low>mid)
{
return qmin(low,high,index*2+1);
}
else
{
return min(qmin(low,mid,index*2),qmin(mid+1,high,index*2+1));
}
}
}
int main()
{
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%d",&height[i]);
build(1,n,1);
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",qmax(a,b,1)-qmin(a,b,1));
}
return 0;
}
{
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%d",&height[i]);
build(1,n,1);
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",qmax(a,b,1)-qmin(a,b,1));
}
return 0;
}
本文介绍了一种使用线段树实现区间最大值和最小值查询的高效算法。该算法适用于处理大规模数据集上的动态范围查询问题,通过预处理将查询时间复杂度降低到对数级别。
3198

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



