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.
【题目分析】
学习一下ST算法。nlogn的预处理和O(1)的查询。复杂度和线段树相同,常熟略小。
【代码】
#include <cstdio>
#include <cmath>
int mi[50001][17],mx[50001][17],a[50001],n,q,l,r;
inline int max(int a,int b){return a>b?a:b;}
inline int min(int a,int b){return a>b?b:a;}
inline void init()
{
int m=(int)((log(n*1.0))/log(2.0));
for (int i=1;i<=n;++i) mi[i][0]=mx[i][0]=a[i];
for (int i=1;i<=m;++i)
for (int j=1;j<=n;++j)
{
mi[j][i]=mi[j][i-1],mx[j][i]=mx[j][i-1];
if(j+(1<<(i-1))<=n) mx[j][i]=max(mx[j][i],mx[j+(1<<(i-1))][i-1]);
if(j+(1<<(i-1))<=n) mi[j][i]=min(mi[j][i],mi[j+(1<<(i-1))][i-1]);
}
}
inline int ri(int l,int r)
{
int m=(int)(log((r-l+1)*1.0)/log(2.0));
return min(mi[l][m],mi[r-(1<<m)+1][m]);
}
inline int rx(int l,int r)
{
int m=(int)(log((r-l+1)*1.0)/log(2.0));
return max(mx[l][m],mx[r-(1<<m)+1][m]);
}
int main()
{
scanf("%d%d",&n,&q);
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
init();
for (int i=1;i<=q;++i)
{
scanf("%d%d",&l,&r);
printf("%d\n",rx(l,r)-ri(l,r));
}
}