Balanced Lineup(POJ - 3264)

Balanced Lineup(POJ - 3264)

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..  NQ+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

模板题,直接用ST表查询区间的最值相减即可.

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=50005;
const int SZ=31;// 
int maxn[N][SZ],minn[N][SZ],a[N];
int n,q,i,j;
int main()
{
    scanf("%d%d",&n,&q);
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        maxn[i][0]=a[i];//maxn[i][0],即从下标i开始的长度为1的最值 
        minn[i][0]=a[i];
    }
    for(j=1;j<SZ;j++)
    {
        for(i=1;i<=n;i++)
        {
            if(i+(1<<j)-1<=n)
            {
                maxn[i][j]=max(maxn[i][j-1],maxn[i+(1<<(j-1))][j-1]);//子区间合并 
                minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
            }
        }
    }
    while(q--)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        if(l>r)
        swap(l,r);
        int k=log2(r-l+1);
        int MAX=max(maxn[l][k],maxn[r-(1<<k)+1][k]);//此处有maxn[r-(1<<k)+1][k]的原因,因为1<<k不一定等于r-l+1。
                                                    //不加它会造成查询区间不全.但是这样也会造成查询重叠
        int MIN=min(minn[l][k],minn[r-(1<<k)+1][k]);
        printf("%d\n",MAX-MIN);
    }
} 
View Code
 

猜你喜欢

转载自www.cnblogs.com/switch-waht/p/11394073.html