POJ 3264 Balanced Lineup(RMQ_ST)

来源:互联网 发布:applewatch怎么解锁mac 编辑:程序博客网 时间:2024/04/29 19:55

题目链接:http://poj.org/problem?id=3264


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 ≤ A ≤ B ≤ N), 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 31734251 54 62 2

Sample Output

630

Source

USACO 2007 January Silver


PS:

百度百科RMQ:http://baike.baidu.com/view/1536346.htm?fr=aladdin

RMQ:http://blog.csdn.net/zztant/article/details/8535764


代码如下:

#include <cstdio>#include <cstring>#include <cmath>#include <iostream>using namespace std;const int MAXN = 100117;int n,query;int num[MAXN];int F_Min[MAXN][20],F_Max[MAXN][20];void Init(){    for(int i = 1; i <= n; i++)    {        F_Min[i][0] = F_Max[i][0] = num[i];    }    for(int i = 1; (1<<i) <= n; i++)  //按区间长度递增顺序递推    {        for(int j = 1; j+(1<<i)-1 <= n; j++)  //区间起点        {            F_Max[j][i] = max(F_Max[j][i-1],F_Max[j+(1<<(i-1))][i-1]);            F_Min[j][i] = min(F_Min[j][i-1],F_Min[j+(1<<(i-1))][i-1]);        }    }}int Query_max(int l,int r){    int k = (int)(log(double(r-l+1))/log((double)2));    return max(F_Max[l][k], F_Max[r-(1<<k)+1][k]);}int Query_min(int l,int r){    int k = (int)(log(double(r-l+1))/log((double)2));    return min(F_Min[l][k], F_Min[r-(1<<k)+1][k]);}int main(){    int a,b;    scanf("%d %d",&n,&query);    for(int i = 1; i <= n; i++)        scanf("%d",&num[i]);    Init();    while(query--)    {        scanf("%d %d",&a,&b);        //printf("区间%d到%d的最大值为:%d\n",a,b,Query_max(a,b));        //printf("区间%d到%d的最小值为:%d\n",a,b,Query_min(a,b));        printf("%d\n",Query_max(a,b)-Query_min(a,b));    }    return 0;}


1 0
原创粉丝点击