Description
For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.
Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.
Input
Lines 2.. N+1: Line i+1 contains a single integer that is the height of cow i
Lines N+2.. N+ Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
#include <stdio.h> #include <string.h> #include <algorithm> #include <math.h> #include <vector> #include <iostream> using namespace std; #define INF 0x3f3f3f3f #define N 200000 int A[N]; struct node { int l, r; int s,st; } tree[N*4]; void init() { for(int i=0;i<4*N;i++) tree[i].st=INF; } void build(int l, int r, int rt) { tree[rt].l = l; tree[rt].r = r; if(l == r) { tree[rt].s = A[l]; return ; } int mid = (l+r)/2; build(l, mid, rt*2); build(mid+1, r, rt*2+1); tree[rt].s = max(tree[rt*2].s ,tree[rt*2+1].s); } int query(int l, int r, int rt) { if(tree[rt].l == l && tree[rt].r == r) { return tree[rt].s; } int mid = (tree[rt].l+tree[rt].r)/2; if(r <= mid) return query(l, r, rt*2); else if(l > mid) return query(l, r, rt*2+1); else { int ll, rr; ll = query(l, mid, rt*2); rr = query(mid+1, r, rt*2+1); return max(ll,rr) ; } } void build1(int l, int r, int rt) { tree[rt].l = l; tree[rt].r = r; if(l == r) { tree[rt].st = A[l]; return ; } int mid = (l+r)/2; build1(l, mid, rt*2); build1(mid+1, r, rt*2+1); tree[rt].st = min(tree[rt*2].st ,tree[rt*2+1].st); } int query1(int l, int r, int rt) { if(tree[rt].l == l && tree[rt].r == r) { return tree[rt].st; } int mid = (tree[rt].l+tree[rt].r)/2; if(r <= mid) return query1(l, r, rt*2); else if(l > mid) return query1(l, r, rt*2+1); else { int ll, rr; ll = query1(l, mid, rt*2); rr = query1(mid+1, r, rt*2+1); return min(ll,rr) ; } } int main() { int n, i, m, ans, a, b, ans1; while(~scanf("%d%d", &n,&m)) { for(i = 1; i <= n; i++) scanf("%d", &A[i]); build(1, n, 1); init(); build1(1, n, 1); for(i=0; i<m; i++) { scanf("%d%d",&a,&b); ans=query(a, b, 1); ans1=query1(a, b, 1); printf("%d\n",ans-ans1); } } return 0; }