poj 3264 Balanced Lineup (简单 RMQ )

来源:互联网 发布:计算机通信与网络答案 编辑:程序博客网 时间:2024/06/15 22:01
Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 29174 Accepted: 13743Case 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 andQ.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2..N+Q+1: Two integers A and B (1 ≤ABN), representing the range of cows from A toB 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

Source

USACO 2007 January Silver

题意:求区间最大值和最小值的差值。
分析:简单rmq模板题。

代码:
#include<cstdio>#include<iostream>#include<cstring>//#include<algorithm>#include<cmath>using namespace std;int N;int h[50010];int dp1[50010][40];int dp2[50010][40];int min1(int a,int b){    return a>b?b:a;}int max1(int a,int b){    return a>b?a:b;}void mk_rmq(){    int i,j;    for(i=1;i<=N;i++)    {        dp1[i][0]=h[i];        dp2[i][0]=h[i];    }    for(j=1;(1<<j)<=N;j++)    {        for(i=1;i+(1<<j)-1<=N;i++)        {            dp1[i][j]=max1(dp1[i][j-1],dp1[i+(1<<(j-1))][j-1]);            dp2[i][j]=min1(dp2[i][j-1],dp2[i+(1<<(j-1))][j-1]);        }    }}int q_rmq(int l,int r){    int k=(int)(log((r-l+1)*1.0)/log(2.0));    int min_h=min1(dp2[l][k],dp2[r-(1<<k)+1][k]);    int max_h=max1(dp1[l][k],dp1[r-(1<<k)+1][k]);    return max_h-min_h;}int main(){    int Q,i,l,r;    while(scanf("%d%d",&N,&Q)!=EOF)    {        for(i=1;i<=N;i++)            scanf("%d",&h[i]);        mk_rmq();        for(i=0;i<Q;i++)        {            scanf("%d%d",&l,&r);            printf("%d\n",q_rmq(l,r));        }    }    return 0;}



12027611

fukan

3264

Accepted

15972K

1891MS

C++

1142B

2013-08-23 09:57:31