#include<iostream>
#include<string>
#include <cstdlib>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 1e5 + 5;
struct node
{
int l,r;
int maxn, minn;
}tree[N*3];
int a[N];
void Build(int i, int l, int r)
{
tree[i].l = l;
tree[i].r = r;
if (l == r)
{
tree[i].maxn = a[l];
tree[i].minn = a[l];
return;
}
int mid = (l+r) >> 1;
Build(i<<1, l, mid);
Build(i<<1|1, mid +1, r);
tree[i].maxn = max(tree[i<<1].maxn, tree[i<<1|1].maxn);
tree[i].minn = min(tree[i<<1].minn, tree[i<<1|1].minn);
}
int Querymax(int i, int a, int b)
{
if (a == tree[i].l && b == tree[i].r)
{
return tree[i].maxn;
}
int mid = (tree[i].l + tree[i].r) >> 1;
if (b <= mid) Querymax(i<<1, a, b);
else if(a > mid) Querymax(i<<1|1, a, b);
else
{
return max(Querymax(i<<1,a,mid), Querymax(i<<1|1, mid + 1, b));
}
}
int Querymin(int i, int a, int b)
{
if (a == tree[i].l && b == tree[i].r)
{
return tree[i].minn;
}
int mid = (tree[i].l + tree[i].r) >> 1;
if (b <= mid) Querymin(i<<1, a, b);
else if(a > mid) Querymin(i<<1|1, a, b);
else
{
return min(Querymin(i<<1,a,mid), Querymin(i<<1|1, mid + 1, b));
}
}
int main()
{
int n, q;
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
Build(1,1,n);
for (int i = 0; i < q; i++)
{
int t1, t2;
scanf("%d %d", &t1, &t2);
printf("%d\n",Querymax(1,t1,t2)-Querymin(1,t1,t2));
}
}
题目链接 http://poj.org/problem?id=3264