是summer training code section里的一道题目,当时没有做出来。由于第一次接触线段树,一开始尝试用min_element() 和 max_element(),结果必然是TLE了。。
另外这道题目的坑爹之处就是用 cin、cout 会TLE,换成scanf、printf 就没有问题。看来还是 cstdio 比较快一些。
其实是线段树中非常简单的一道题目。附上代码:
#include<iostream>
#include<climits>
#include<cstdio>
using namespace std;
typedef struct{
int l;
int r;
int Min;
int Max;
} NODE;
NODE st[220000];
int height[50001];
int MIN, MAX;
void build(int root, int l, int r){
st[root].l = l;
st[root].r = r;
if(l != r){
int mid = (l + r) >> 1;
build(root << 1, l, mid);
build(root << 1 | 1, mid + 1, r);
st[root].Min = min(st[root << 1].Min, st[root << 1 | 1].Min);
st[root].Max = max(st[root << 1].Max, st[root << 1 | 1].Max);
}
else{
st[root].Min = height[l];
st[root].Max = height[l];
}
void query(int root, int l, int r){
if(MIN <= st[root].Min && MAX >= st[root].Max)
return;
int mid = (st[root].l + st[root].r) >> 1;
if(st[root].l == l && st[root].r == r){
MAX = max(st[root].Max, MAX);
MIN = min(st[root].Min, MIN);
}else if(mid < l){
query(root << 1 | 1, l, r);
}else if(mid >= r){
query((root << 1), l, r);
}else{
query(root << 1 | 1, mid + 1, r);
query((root << 1), l, mid);
}
}
int main(){
int N, Q;
cin >> N >> Q;
for(int i = 1; i <= N; i++)
scanf("%d", &height[i]);
build(1, 1, N);
while(Q--){
int l, r;
scanf("%d %d", &l, &r);
MAX = -1;
MIN = INT_MAX;
query(1, l, r);
printf("%d\n", MAX - MIN);
}
return 0;
}