J - Balanced Lineup

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 ≤ ABN), 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.

 Input

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

 Output

6
3
0

解决思路:

        这里使用了ST表,推荐这个网站。

        实际上我这个代码完全就是使用了这个网站的模板。

AC代码:

#include 

using namespace std;

const int logn = 21;
const int maxn = 2000001;
int _fmax[maxn][logn + 1];
int _fmin[maxn][logn + 1];
int Logn[maxn + 1];

void pre()
{
    Logn[1] = 0;
    Logn[2] = 1;
    for (int i = 3; i < maxn; i++)
    {
        Logn[i] = Logn[i / 2] + 1;
    }
}

int main()
{
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++)
    {
        int num;
        scanf("%d", &num);
        _fmax[i][0] = _fmin[i][0] = num;
    }
    //预处理部分
    pre();
    for (int j = 1; j <= logn; j++)
    {
        for (int i = 1; i + (1 << j) - 1 <= n; i++)
        {
            _fmax[i][j] = max(_fmax[i][j - 1], _fmax[i + (1 << (j - 1))][j - 1]);
            _fmin[i][j] = min(_fmin[i][j - 1], _fmin[i + (1 << (j - 1))][j - 1]);
        }
    }
    //询问
    for (int i = 1; i <= m; i++)
    {
        int x , y;
        scanf("%d %d", &x, &y);
        int s = Logn[y - x + 1];
        printf("%d\n", max(_fmax[x][s], _fmax[y - (1 << s) + 1][s]) - min(_fmin[x][s], _fmin[y - (1 << s) + 1][s]));
    }
    return 0;
}

你可能感兴趣的:(c++,算法)