题目链接:http://poj.org/problem?id=3264
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.
题意描述:n个数排成一排形成数组,Q个询问,每个询问给出两个数a和b,求出数组中[a,b]里最大值和最小值的差。
算法分析:可以用线段树做,在这里介绍RMQ算法。
RMQ:预处理O(nlogn),然后每次查询O(1)。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>
#define inf 0x7fffffff
using namespace std;
const int maxn=+; int n,q;
int an[maxn],dmax[maxn][],dmin[maxn][]; void RMQ_init()
{
for (int i= ;i<=n ;i++) dmax[i][]=dmin[i][]=an[i];
for (int j= ;(<<j)<=n ;j++)
{
for (int i= ;i+(<<j)-<=n ;i++)
{
dmax[i][j]=max(dmax[i][j-],dmax[i+(<<(j-))][j-]);
dmin[i][j]=min(dmin[i][j-],dmin[i+(<<(j-))][j-]);
}
}
} int RMQ(int L,int R)
{
int k=;
while ((<<(k+))<=R-L+) k++;
int maxnum=max(dmax[L][k],dmax[R-(<<k)+][k]);
int minnum=min(dmin[L][k],dmin[R-(<<k)+][k]);
return maxnum-minnum;
} int main()
{
while (scanf("%d%d",&n,&q)!=EOF)
{
for (int i= ;i<=n ;i++) scanf("%d",&an[i]);
RMQ_init();
int a,b;
for (int i= ;i<q ;i++)
{
scanf("%d%d",&a,&b);
printf("%d\n",RMQ(a,b));
}
}
return ;
}