//poj3264 Balanced Lineup
//线段树
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAXN = 50010;
struct MinMax{
int min, max;
};
struct Node{
struct MinMax minmax;
int left, right;
}tree[MAXN * 3];
int arrCow[MAXN];
int nN, nM;
inline int Min(int x, int y){
return x < y ? x : y;
}
inline int Max(int x, int y){
return x > y ? x : y;
}
void build(int root, int left, int right){
tree[root].left = left;
tree[root].right = right;
if(left == right) tree[root].minmax.max = tree[root].minmax.min = arrCow[left];
else{
int mid = (left + right) >> 1;
build(root * 2, left, mid);
build(root * 2 + 1, mid + 1, right);
tree[root].minmax.min = Min(tree[root * 2].minmax.min, tree[root * 2 + 1].minmax.min);
tree[root].minmax.max = Max(tree[root * 2].minmax.max, tree[root * 2 + 1].minmax.max);
}
}
struct MinMax search(int root, int left, int right){
if(tree[root].left == left && tree[root].right == right)
return tree[root].minmax;
int mid = (tree[root].left + tree[root].right) >> 1;
if(mid >= right)
return search(root * 2, left, right);
else if(mid < left)
return search(root * 2 + 1, left, right);
else{
struct MinMax tmp1, tmp2, tmp3;
tmp1 = search(root * 2, left, mid);
tmp2 = search(root * 2 + 1, mid + 1, right);
tmp3.min = Min(tmp1.min, tmp2.min);
tmp3.max = Max(tmp1.max, tmp2.max);
return tmp3;
}
}
int main(){
while(cin >> nN >> nM){
memset(tree, 0, sizeof(tree));
memset(arrCow, 0, sizeof(arrCow));
for(int i = 1; i <= nN; i++)
scanf("%d", arrCow + i);
build(1, 1, nN);
for(int i = 1; i <= nM; i++){
int nL, nR;
scanf("%d %d", &nL, &nR);
struct MinMax tmp = search(1, nL, nR);
cout << tmp.max - tmp.min << endl;
}
}
return 0;
}
poj3264_Balanced Lineup_线段树
最新推荐文章于 2019-08-07 13:02:14 发布