POJ3264 http://poj.org/problem?id=3264
线段树模版。
题目大意:
Q次区间查询。
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 50000 + 5;
int a[maxn];
int miv[maxn * 4];
int mav[maxn * 4];
int ans1 = -0x3f3f3f;
int ans2 = 0x3f3f3f;
void pushup(int i) {
miv[i] = min(miv[i << 1], miv[i << 1 | 1]);
mav[i] = max(mav[i << 1], mav[i << 1 | 1]);
}
void build(int i,int l,int r) {
if(l == r) {
miv[i] = a[l];
mav[i] = a[l];
return;
}
int mid = (l + r) >> 1;
build(i << 1, l, mid);
build(i << 1 | 1, mid + 1, r);
pushup(i);
}
void query(int i, int l, int r, int x, int y) {
if(x <= l && r <= y) {
ans1 = max(ans1, mav[i]);
ans2 = min(ans2, miv[i]);
}else {
int mid = (l + r) >> 1;
if(x <= mid) {
query(i << 1, l, mid, x, y);
}
if(y > mid) {
query(i << 1 | 1, mid + 1, r, x, y);
}
}
}
int main() {
int N, Q;
int w, b;
while(~scanf("%d%d",&N,&Q)) {
for(int i = 1; i <= N; i++) {
scanf("%d",&a[i]);
}
build(1,1,N);
while(Q--) {
ans1 = -0x3f3f3f;
ans2 = 0x3f3f3f;
scanf("%d%d",&w,&b);
query(1,1,N,w,b);
printf("%d\n",ans1 - ans2);
}
}
return 0;
}