POJ 3264-Balanced Lineup(RMQ-ST演算法)

kewlgrl發表於2017-04-05

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 51826   Accepted: 24285
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

Source


求N個數中給定區間L-R中最大值與最小值的差。

以前這題作為入門題用線段樹搞了搞,突然翻出來用RMQ水了一發。

坑爹的是cin、cout會超時…


#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<map>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
#define MAXN 50010
int a[MAXN],dpmin[MAXN][20],dpmax[MAXN][20];
int n,q;
void rmq()
{
    int temp=(int)(log((double)n)/log(2.0));
    for(int i=0; i<n; i++)
        dpmin[i][0]=a[i],dpmax[i][0]=a[i];
    for(int j=1; j<=temp; j++)
        for(int i=0; i<=n-(1<<j); i++)
        {
            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 Minimum(int s,int e)
{
    int k=(int)(log((double)e-s+1)/log(2.0));
    return min(dpmin[s][k],dpmin[e-(1<<k)+1][k]);
}
int Maxmum(int s,int e)
{
    int k=(int)(log((double)e-s+1)/log(2.0));
    return max(dpmax[s][k],dpmax[e-(1<<k)+1][k]);
}
int main()
{
    scanf("%d%d",&n,&q);
    memset(a,0,sizeof(a));
    memset(dpmin,0,sizeof(dpmin));
    memset(dpmax,0,sizeof(dpmax));
    for(int i=0; i<n; ++i)//下標0-n-1
        scanf("%d",&a[i]);
    rmq();//dp預處理
    for(int i=0; i<q; ++i)
    {
        int s,e;
        scanf("%d%d",&s,&e);
        --s,--e;
        if(s==e) printf("0\n");
        else printf("%d\n",Maxmum(s,e)-Minimum(s,e));
    }
    return 0;
}


相關文章