POJ 3264 Balanced Lineup【RMQ-ST算法-区间最值】

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

很好的参考资料:http://s99f.blog.163.com/blog/static/3511836520094229354265/
代码如下:
View Code
#include<stdio.h>

#include<string.h>

#include<iostream>

#include<math.h> 

#include<algorithm>

using namespace std; 

#define N 50005 

int dpmin[N][20], dpmax[N][20]; 

int main()

{

    int i, j, n, m;

    scanf("%d%d", &n, &m); 

    memset(dpmin, 0, sizeof(dpmin));

    memset(dpmax, 0, sizeof(dpmax));

    for(i=1; i<=n; i++)

    {

        scanf("%d", &dpmin[i][0]);

        dpmax[i][0]=dpmin[i][0]; 

    }

    int mm=floor(log(1.0*n)/log(2.0));

    for(j=1; j<=mm; j++)

        for(i=n; i>=1; i--)

        {

            if((i+(1<<(j-1)))<=n)

            { 

                dpmin[i][j]=min(dpmin[i][j-1], dpmin[i+(1<<(j-1))][j-1]);

                dpmax[i][j]=max(dpmax[i][j-1], dpmax[i+(1<<(j-1))][j-1]);

            } 

        }

    int x, y; 

    for(int i=1; i<=m; i++)

    {

        scanf("%d%d", &x, &y);

        int  mid=floor(log(y*1.0-x+1)/log(2.0));

        int maxnum=max(dpmax[x][mid], dpmax[y-(1<<mid)+1][mid]);

        int minnum=min(dpmin[x][mid], dpmin[y-(1<<mid)+1][mid]);

        printf("%d\n", maxnum-minnum);

    }

}

 



你可能感兴趣的:(poj)