Balanced Lineup

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 ≤ 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.

Sample Input

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

Sample Output

6
3
0
#include<stdio.h>
int max(int x,int y)
{
    if(x>y) return x;
    else return y;
}
int min(int x,int y)
{
    if(x<y) return x;
    else return y;
}

#define N 60000

int stmax[N][100],stmin[N][200],mn[N];
int a[N];

int t,q,n;
int x,y;

void init()
{
    mn[0]=-1;
    for (int i=1;i<=n;i++)
    {
        mn[i]=((i & (i-1))==0) ? mn[i-1]+1 : mn[i-1];
        stmax[i][0]=stmin[i][0]=a[i];
    }
    for (int j=1;j<=mn[n];j++)
        for (int i=1;i+(1<<j)-1<=n;i++)
        {
            stmax[i][j]=max(stmax[i][j-1],stmax[i+(1<<(j-1))][j-1]);
            stmin[i][j]=min(stmin[i][j-1],stmin[i+(1<<(j-1))][j-1]);
        }
}

int rmq_max(int L,int R)
{
    int k=mn[R-L+1];
    return max(stmax[L][k],stmax[R-(1<<k)+1][k]);
}

int rmq_min(int L,int R)
{
    int k=mn[R-L+1];
    return min(stmin[L][k],stmin[R-(1<<k)+1][k]);
}
int b[3000000]={0};
int main()
{

    while (scanf("%d %d",&n,&q)!=EOF)
    {
        //scanf("%d",&n);
        for (int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        init();
        int t=1;
        //scanf("%d",&q);
        while (q--)
        {
            scanf("%d%d",&x,&y);
            b[t++]=rmq_max(x,y)-rmq_min(x,y);
        }
        for(int i=1;i<t;i++)
        {
            printf("%d\n",b[i]);
        }
    }
    return 0;
}

 

全部评论

相关推荐

09-14 20:51
四川大学 Java
慢热的鲸鱼在学习:985加粗就行了,第二个项目来不及准备也没事,省的写了问你你还不会。你只需准备面试八股和项目场景,剩下的交给985。即使面不过也没事,面试经验是最重要的,你现在不缺时间
简历中的项目经历要怎么写
点赞 评论 收藏
分享
码农索隆:传音老登来也。 但是这个我不知道怎么回答,不仅仅传音吧,很多公司在候选人不第一时间接受offer或主动将报道时间延期时,都会再从池子里面捞人,直到l捞到满足公司所有要求的人。
秋招的第一个offer,...
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
09-29 11:20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务