poj3264(线段树区间求最值)

时间:2022-09-06 21:43:10

题目连接:http://poj.org/problem?id=3264

题意:给定Q(1<=Q<=200000)个数A1,A2,```,AQ,多次求任一区间Ai-Aj中最大数和最小数的差。

线段树功能:区间求最值,O(logN)复杂度查询

#pragma comment(linker,"/STACK:102400000,102400000")
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstdlib>
#include <stack>
#include <vector>
#include <set>
#include <map>
#define LL long long
#define mod 1000000007
#define inf 0x3f3f3f3f
#define N 50010
#define FILL(a,b) (memset(a,b,sizeof(a)))
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int mx[N<<],mn[N<<];
void Pushup(int rt)
{
mn[rt]=min(mn[rt<<],mn[rt<<|]);
mx[rt]=max(mx[rt<<],mx[rt<<|]);
}
void build(int l,int r,int rt)
{
if(l==r)
{
int x;
scanf("%d",&x);
mn[rt]=mx[rt]=x;
return;
}
int m=(l+r)>>;
build(lson);
build(rson);
Pushup(rt);
}
int querymin(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
return mn[rt];
}
int m=(l+r)>>;
int res=inf;
if(L<=m)res=min(res,querymin(L,R,lson));
if(m<R)res=min(res,querymin(L,R,rson));
return res;
}
int querymax(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
return mx[rt];
}
int m=(l+r)>>;
int res=;
if(L<=m)res=max(res,querymax(L,R,lson));
if(m<R)res=max(res,querymax(L,R,rson));
return res;
}
int main()
{
int n,m;
int a,b;
while(scanf("%d%d",&n,&m)>)
{
build(,n,);
while(m--)
{
scanf("%d%d",&a,&b);
int tallest=querymax(a,b,,n,);
int shortest=querymin(a,b,,n,);
printf("%d\n",tallest-shortest);
}
}
}