http://poj.org/problem?id=3264
题意:现有N个数字,问你在区间[a, b]之间最大值与最小值的差值为多少?
分析:线段树模板,不过需要有两个查询,一个查询在该区间的最大值,一个查询在该区间的最小值,最后两者结果相减即可。
#include <iostream> #include <stdio.h> #include <string.h> #include <string> #include <vector> #include <algorithm> #include <map> #include <queue> #include <stack> #include <math.h> using namespace std; #define met(a, b) memset(a, b, sizeof(a)) #define maxn 51000 #define INF 0x3f3f3f3f const int MOD = 1e9+7; typedef long long LL; #define lson rt<<1 #define rson rt<<1|1 int A[maxn], n; struct node { int l, r, maxs, mins; }tree[maxn<<2]; void build(int l, int r, int rt) { tree[rt].l = l; tree[rt].r = r; if(l == r) { tree[rt].maxs = A[l]; tree[rt].mins = A[l]; return ; } int mid = (l+r)/2; build(l, mid, lson); build(mid+1, r, rson); tree[rt].maxs = max(tree[lson].maxs, tree[rson].maxs); tree[rt].mins = min(tree[lson].mins, tree[rson].mins); } int query1(int l, int r, int rt) { if(tree[rt].l==l && tree[rt].r==r) return tree[rt].maxs; int mid = (tree[rt].l+tree[rt].r)/2; if(r<=mid) return query1(l, r, lson); else if(l>mid) return query1(l, r, rson); else { int lmaxs = query1(l, mid, lson); int rmaxs = query1(mid+1, r, rson); int maxs = max(lmaxs, rmaxs); return maxs; } } int query2(int l, int r, int rt) { if(tree[rt].l==l && tree[rt].r==r) return tree[rt].mins; int mid = (tree[rt].l+tree[rt].r)/2; if(r<=mid) return query2(l, r, lson); else if(l>mid) return query2(l, r, rson); else { int lmins = query2(l, mid, lson); int rmins = query2(mid+1, r, rson); int mins = min(lmins, rmins); return mins; } } int main() { int q, a, b; while(scanf("%d %d", &n, &q)!=EOF) { for(int i=1; i<=n; i++) scanf("%d", &A[i]); build(1, n, 1); while(q --) { scanf("%d %d", &a, &b); int p = query1(a, b, 1);///查询最大值 int q = query2(a, b, 1);///查询最小值 printf("%d\n", p-q); } } return 0; }