题目链接:http://poj.org/problem?id=3264
Time Limit: 5000MS Memory Limit: 65536K Case Time Limit: 2000MS

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

Line 1: Two space-separated integers, N and Q
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

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

Sample Input

6 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

Problem solving report:

Description: 给一些数,求出[l,r]区间里的最大值和最小值,计算差值。
Problem solving: 线段树模板题。

Accepted Code:

/* 
 * @Author: lzyws739307453 
 * @Language: C++ 
 */
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
const int MAXN = 50005;
struct Tree {
    int max_, min_;
}segTree[MAXN << 2];
void Create(int l, int r, int rt) {
    if (!(r != l)) {
        scanf("%d", &segTree[rt].max_);
        segTree[rt].min_ = segTree[rt].max_;
        return ;
    }
    int mid = l + ((r - l) >> 1);
    Create(l, mid, rt << 1);
    Create(mid + 1, r, rt << 1 | 1);
    segTree[rt].max_ = max(segTree[rt << 1].max_, segTree[rt << 1 | 1].max_);
    segTree[rt].min_ = min(segTree[rt << 1].min_, segTree[rt << 1 | 1].min_);
}
int QueryMax(int Ql, int Qr, int l, int r, int rt) {
    if (Ql <= l && Qr >= r)
        return segTree[rt].max_;
    int cnt = 0;
    int mid = l + ((r - l) >> 1);
    if (Ql <= mid)
        cnt = max(cnt, QueryMax(Ql, Qr, l, mid, rt << 1));
    if (Qr > mid)
        cnt = max(cnt, QueryMax(Ql, Qr, mid + 1, r, rt << 1 | 1));
    return cnt;
}
int QueryMin(int Ql, int Qr, int l, int r, int rt) {
    if (Ql <= l && Qr >= r)
        return segTree[rt].min_;
    int cnt = inf;
    int mid = l + ((r - l) >> 1);
    if (Ql <= mid)
        cnt = min(cnt, QueryMin(Ql, Qr, l, mid, rt << 1));
    if (Qr > mid)
        cnt = min(cnt, QueryMin(Ql, Qr, mid + 1, r, rt << 1 | 1));
    return cnt;
}
int main() {
    int l, r, n, m;
    while (~scanf("%d%d", &n, &m)) {
        Create(1, n, 1);
        while (m--) {
            scanf("%d%d", &l, &r);
            printf("%d\n", QueryMax(l, r, 1, n, 1) - QueryMin(l, r, 1, n, 1));
        }
    }
    return 0;
}