Balanced Lineup 倍增思想到ST表RMQ

 
                            Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 36864   Accepted: 17263
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 ≤ 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 题目抽象:求数组区间[a,b]之间的最大值与最小值的差。
 #include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int INF=0x4fffffff;
const int MS=; int a[MS];
int minv[MS][];
int maxv[MS][]; int N,Q; void RMQ_init()
{
for(int i=;i<N;i++)
minv[i][]=maxv[i][]=a[i];
for(int j=;(<<j)<=N;j++)
{
for(int i=;i+(<<j)-<N;i++)
{
minv[i][j]=min(minv[i][j-],minv[i+(<<(j-))][j-]);
maxv[i][j]=max(maxv[i][j-],maxv[i+(<<(j-))][j-]);
}
}
} int query_min(int l,int r)
{
int k=;
while((<<(k+))<(r-l+))
k++;
return min(minv[l][k],minv[r-(<<k)+][k]);
} int query_max(int l,int r)
{
int k=;
while((<<(k+))<(r-l+))
k++;
return max(maxv[l][k],maxv[r-(<<k)+][k]);
} int main()
{
scanf("%d%d",&N,&Q);
for(int i=;i<N;i++)
scanf("%d",&a[i]);
RMQ_init();
while(Q--)
{
int l,r;
scanf("%d%d",&l,&r);
l--;
r--;
int max_v=query_max(l,r);
int min_v=query_min(l,r);
printf("%d\n",max_v-min_v);
}
return ;
}
上一篇:[js开源组件开发]localStorage-cache本地存储的缓存管理


下一篇:SASS使用总结