POJ 3264 Balanced Lineup (st表模版)

 题目

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.. NQ+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from Ato 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 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

 

题解

板子题。只需要维护两个st表即可

 

AC代码

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

const int LOG = 15;

int Max[50000 + 10][16];
int Min[50000 + 10][16];

void st(int n){
    for(int i = 1; i <= n; ++i){
        cin >> Max[i][0];
        Min[i][0] = Max[i][0];
    }
    for(int j = 1; j <= LOG; ++j)
        for(int i = 1; i + (1 << j) - 1 <= n; ++i){
            Max[i][j] = max(Max[i][j - 1], Max[i + (1 << (j - 1))][j - 1]); //等长的两段取max
            Min[i][j] = min(Min[i][j - 1], Min[i + (1 << (j - 1))][j - 1]);
        }
}

void query(int l, int r){
    int len = r - l, LOG1;
    for(LOG1 = 0; (1 << LOG1) <= len; ++LOG1){}
    if(r == l)
        cout << 0 << endl;
    else{
        LOG1--;
        int temp_max = max(Max[l][LOG1], Max[r - (1 << LOG1) + 1][LOG1]);
        int temp_min = min(Min[l][LOG1], Min[r - (1 << LOG1) + 1][LOG1]);
        cout << temp_max - temp_min << endl;
    }
}

int main(){
    //ios::sync_with_stdio(0);
    //cin.tie(0);
    int n ,q;
    //cin >> n >> q; //n头牛,q个询问
    scanf("%d%d", &n, &q);
    st(n);  //建表
    int l, r;
    while(q--){
        //cin >> l >> r;
        scanf("%d%d", &l, &r);
        query(l ,r); //查询
    }
    return 0;
}

 

posted @ 2019-07-31 23:51  Cl0ud_z  阅读(149)  评论(0编辑  收藏  举报