Balanced Lineup -RMQ模板

版权声明:《本文为博主原创文章,转载请注明出处。 》 https://blog.csdn.net/zbq_tt5/article/details/89458935

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

题目大意:

给定N给高度不同的牛,计算给定区间内最大高度和最小高度牛的差值。

题解:

这道题的数据范围是200000*1000000=2*e11

通常一秒内10^6肯定能过 10^7有点勉强 10^8。。就悬了

O(logn) 
额 非常大 long long内都可以

O(n) 
10^7

O(nlogn) 
10^5 ~ 5 * 10^5

O(n^2) 
1000 ~ 5000

O(n^3) 
200 ~ 500

O(2^n) 
20 ~ 24

O(n!) 
12

转自:https://blog.csdn.net/DoloresL/article/details/78159895

如果按照普通的方法,肯定会超时的,这个时候我用的是RMQ,时间复杂度是nlogn,这样就解决了!


#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e6+5;
int dp_max[maxn][20];
int dp_min[maxn][20];
int mm[maxn],b[maxn];

void initRMQ(int n,int b[])
{
    mm[0]=-1;
    for(int i=1;i<=n;++i)
    {
        mm[i]=((i&(i-1))==0)?mm[i-1]+1:mm[i-1];
        dp_max[i][0]=b[i];
        dp_min[i][0]=b[i];
    }
    for(int j=1;j<=mm[n];j++)
    {
        for(int i=1;i+(1<<j)-1<=n;i++)
        {
            dp_max[i][j]=max(dp_max[i][j-1],dp_max[i+(1<<(j-1))][j-1]);
            dp_min[i][j]=min(dp_min[i][j-1],dp_min[i+(1<<(j-1))][j-1]);
        }
    }
}
int rmq_max(int x,int y)
{
    int k=mm[y-x+1];
    return max(dp_max[x][k],dp_max[y-(1<<k)+1][k]);
}

int rmq_min(int x,int y)
{
    int k=mm[y-x+1];
    return min(dp_min[x][k],dp_min[y-(1<<k)+1][k]);
}

int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;++i)
    {
        scanf("%d",&b[i]);
    }
    initRMQ(n,b);
    for(int i=1;i<=m;++i)
    {
        int a,b;
        cin>>a>>b;
        printf("%d\n",rmq_max(a,b)-rmq_min(a,b));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zbq_tt5/article/details/89458935