POJ - 3264 Balanced Lineup(線段樹維護最值)

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 56270   Accepted: 26367
Case 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 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 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

Source


題意:給出一個序列,求[l, r]區間最大值與最小值的差;

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int N = 50000 + 10, inf = 0x3f3f3f3f;
int n, m;
struct xx{
    int l, r, maxi, mini;
} T[N<<2];

void Pushup(int k){
    T[k].maxi = max(T[k<<1].maxi, T[k<<1|1].maxi);
    T[k].mini = min(T[k<<1].mini, T[k<<1|1].mini);
}

void Build(int l, int r, int k){
    T[k].l = l, T[k].r = r, T[k].maxi = -inf, T[k].mini = inf;
    if(l == r){
        int x;
        scanf("%d", &x);
        T[k].maxi = T[k].mini = x;
        return;
    }
    int mid = (l+r)>>1;
    Build(l, mid, k<<1);
    Build(mid+1, r, k<<1|1);
    Pushup(k);
}

int Maxi, Mini;
void Query(int l, int r, int k){
    //printf("__%d\n", k);
    if(l <= T[k].l && r >= T[k].r){
        Maxi = max(Maxi, T[k].maxi);
        Mini = min(Mini, T[k].mini);
        //printf("%d %d\n", Maxi, Mini);
        return;
    }
    if(T[k].l == T[k].r) return;
    int mid = (T[k].l+T[k].r)>>1;
    if(l > mid) Query(l, r, k<<1|1);
    else if(r <= mid) Query(l, r, k<<1);
    else{
        Query(l ,mid, k<<1);
        Query(mid+1, r, k<<1|1);
    }
}

int main(){
    while(scanf("%d%d", &n, &m) == 2){
        Build(1, n, 1);
        for(int i = 0; i < m; i++){
            int u, v;
            scanf("%d%d", &u, &v);
            Maxi = -inf, Mini = inf;
            Query(u, v, 1);
            printf("%d\n", Maxi - Mini);
        }
    }
}


發佈了133 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章