Balanced Lineup

来源:互联网 发布:java实现解压缩zip 编辑:程序博客网 时间:2024/05/02 04:23

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 31734251 54 62 2

Sample Output

630
#include<stdio.h>#include<algorithm>using namespace std;int dp1[100000][25];int dp2[100000][25];int a[100000];int main(){int n,t;scanf("%d%d",&n,&t);for(int i=1;i<=n;i++){scanf("%d",&a[i]);dp1[i][0]=a[i];dp2[i][0]=a[i];}for(int j=1;j<=15;j++)for(int i=1;i+(1<<j)-1<=n;i++){int k=(1<<(j-1));dp1[i][j]=max(dp1[i+k][j-1],dp1[i][j-1]);    dp2[i][j]=min(dp2[i+k][j-1],dp2[i][j-1]);}int a,b;int x,y,m,s;while(t--){scanf("%d%d",&a,&b);if(a==b)  puts("0");else{   for(int i=1;i<=16;i++)   {         m=1<<(i-1); if(a+m<=b && a+2*m>b) { s=i-1;    break; }     }     x=max(dp1[a][s],dp1[b-m+1][s]);   y=min(dp2[a][s],dp2[b-m+1][s]);   printf("%d\n",x-y);}}}

#include<stdio.h>#include<algorithm>using namespace std;int dp1[50010][25];int dp2[50010][25];int a[50010];int main(){int n,t;scanf("%d%d",&n,&t);for(int i=1;i<=n;i++){    scanf("%d",&a[i]);dp1[i][0]=a[i];dp2[i][0]=a[i];}for(int j=1;j<=15;j++)for(int i=1;i+(1<<j)-1<=n;i++){dp1[i][j]=max(dp1[i+(1<<(j-1))][j-1],dp1[i][j-1]);    dp2[i][j]=min(dp2[i+(1<<(j-1))][j-1],dp2[i][j-1]);}int a,b,x,y;while(t--){int i;scanf("%d%d",&a,&b);   for(i=0;i<=15;i++) if(a+(1<<i)-1<=b && a+(1<<(i+1))-1>b)    break;    x=max(dp1[a][i],dp1[b-(1<<i)+1][i]);   y=min(dp2[a][i],dp2[b-(1<<i)+1][i]);   printf("%d\n",x-y);}}


原创粉丝点击