POJ 3264
题意:给定序列,求区间 [x,y] 最大值和最小值的差
标签:区间最值
分析:线段树维护区间最大最小值,分开查询。
还是老问题,POJ流同步关了还是T
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const int mod=1e9+7;
const int maxn=5e4+10;
struct node {
int l,r,k,Max,Min;
} tree[maxn<<2];
int n,m;
int a[maxn];
void push_up(int p){
//tree[p].k=tree[p<<1].k+tree[(p<<1)|1].k;
tree[p].Max=max(tree[p<<1].Max,tree[(p<<1)|1].Max);
tree[p].Min=min(tree[p<<1].Min,tree[(p<<1)|1].Min);
}
void build(int p, int l, int r) {
tree[p].l=l;
tree[p].r=r;
if (l==r) {
tree[p].Max=tree[p].Min=a[l];
return;
}
int m=(l+r)>>1;
build(p<<1,l,m),build((p<<1)|1,m+1,r);
push_up(p);
}
int queryMin(int p, int x, int y) {
if (x<=tree[p].l && y>=tree[p].r) return tree[p].Min;
//push_down(p);
int m=(tree[p].l+tree[p].r)>>1;
int ans=INF;
if (x<=m) ans=min(ans,queryMin(p<<1,x,y));
if (y>m) ans=min(ans,queryMin((p<<1)|1,x,y));
return ans;
}
int queryMax(int p, int x, int y) {
if (x<=tree[p].l && y>=tree[p].r) return tree[p].Max;
//push_down(p);
int m=(tree[p].l+tree[p].r)>>1;
int ans=0;
if (x<=m) ans=max(ans,queryMax(p<<1,x,y));
if (y>m) ans=max(ans,queryMax((p<<1)|1,x,y));
return ans;
}
int main() {
//ios::sync_with_stdio(0);
//cin.tie(0);
//cout.tie(0);
scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++) scanf("%d",&a[i]);
build(1,1,n);
int x,y;
while (m--){
scanf("%d%d",&x,&y);
printf("%d\n",queryMax(1,x,y)-queryMin(1,x,y));
}
return 0;
}