/*Interval Tree*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
struct node {
int l, r;
int MIN, MAX, num;
};
const int maxn = 500010;
const int INF = 100000000;
node tree[maxn << 2];
int n, q;
int Min, Max;
void solve(int root)
{
tree[root].MIN = min(tree[root << 1].MIN, tree[root << 1 | 1].MIN);
tree[root].MAX = max(tree[root << 1].MAX, tree[root << 1 | 1].MAX);
}
void build(int l, int r, int root)
{
tree[root].l = l;
tree[root].r = r;
if (tree[root].l == tree[root].r) {
scanf("%d", &tree[root].num);
tree[root].MIN = tree[root].MAX = tree[root].num;
return;
}
int mid = (l + r) >> 1;
build(l, mid, root << 1);
build(mid + 1, r, root << 1 | 1);
solve(root);
}
void query(int l, int r, int root)
{
if (tree[root].l >= l && tree[root].r <= r) {
Min = min(Min, tree[root].MIN);
Max = max(Max, tree[root].MAX);
return;
}
int mid = (tree[root].l + tree[root].r) >> 1;
if (r <= mid)
query(l, r, root << 1);
else if (l > mid)
query(l, r, root << 1 | 1);
else {
query(l, mid, root << 1);
query(mid + 1, r, root << 1 | 1);
}
}
int main()
{
while (cin >> n >> q) {
build(1, n, 1);
int l, r;
for (int i = 0; i < q; ++i) {
scanf("%d%d", &l, &r);
Min = INF; Max = -INF;
query(l, r, 1);
cout << Max - Min << endl;
}
}
return 0;
}
POJ3264 Balanced Lineup
最新推荐文章于 2020-04-17 16:16:07 发布