您的位置:首页 > 其它

poj 3264 Balanced Lineup 区间极值RMQ

2015-03-18 00:12 465 查看
题目链接: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=50000+10;

int n,q;
int an[maxn],dmax[maxn][16],dmin[maxn][16];

void RMQ_init()
{
for (int i=1 ;i<=n ;i++) dmax[i][0]=dmin[i][0]=an[i];
for (int j=1 ;(1<<j)<=n ;j++)
{
for (int i=1 ;i+(1<<j)-1<=n ;i++)
{
dmax[i][j]=max(dmax[i][j-1],dmax[i+(1<<(j-1))][j-1]);
dmin[i][j]=min(dmin[i][j-1],dmin[i+(1<<(j-1))][j-1]);
}
}
}

int RMQ(int L,int R)
{
int k=0;
while ((1<<(k+1))<=R-L+1) k++;
int maxnum=max(dmax[L][k],dmax[R-(1<<k)+1][k]);
int minnum=min(dmin[L][k],dmin[R-(1<<k)+1][k]);
return maxnum-minnum;
}

int main()
{
while (scanf("%d%d",&n,&q)!=EOF)
{
for (int i=1 ;i<=n ;i++) scanf("%d",&an[i]);
RMQ_init();
int a,b;
for (int i=0 ;i<q ;i++)
{
scanf("%d%d",&a,&b);
printf("%d\n",RMQ(a,b));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: