POJ 3264 Balanced Lineup

              POJ 3264 Balanced Lineup

             ([kuangbin带你飞]专题七 线段树[Cloned]  - G

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

思路:线段树模板 设置两个变量记录每个区间内的最大值和最小值,询问时做差
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#define N 50001
using namespace std;
int n, m;
struct nond {
    int ll, rr;
    int maxn, minn;
    int sum;
}tree[4*N];
void up(int now) {
    tree[now].maxn = max(tree[now*2].maxn, tree[now*2+1].maxn);
    tree[now].minn = min(tree[now*2].minn, tree[now*2+1].minn);
}
void build(int now, int l, int r) {
    tree[now].ll = l; tree[now].rr = r;
    if(l == r) {
        scanf("%d", &tree[now].sum);
        tree[now].maxn = tree[now].minn = tree[now].sum;
        return ;
    }
    int mid = (l+r) / 2;
    build(now*2, l, mid);
    build(now*2+1, mid+1, r);
    up(now);
}
int query(int now, int l, int r) {
    if(tree[now].ll==l && tree[now].rr==r) return tree[now].maxn;
    int mid = (tree[now].ll+tree[now].rr) / 2;
    if(l<=mid && mid<r) return max(query(now*2, l, mid), query(now*2+1, mid+1, r));
    else if(r<=mid) return query(now*2, l, r);
    else return query(now*2+1, l, r);
}
int find(int now, int l, int r) {
    if(tree[now].ll==l && tree[now].rr==r) return tree[now].minn;
    int mid = (tree[now].ll+tree[now].rr) / 2;
    if(l<=mid && mid<r) return min(find(now*2, l, mid), find(now*2+1, mid+1, r));
    else if(r<=mid) return find(now*2, l, r);
    else return find(now*2+1, l, r);
}
int main() {
    scanf("%d%d", &n, &m);
    build(1, 1, n);
    for(int i = 1; i <= m; i++) {
        int a, b;
        scanf("%d%d", &a, &b);
        int x = query(1, a, b);
        int y = find(1, a, b);
        printf("%d\n", x-y);
    }
    return 0;
}

 


 

 

posted @ 2018-03-31 08:31  落云小师妹  阅读(182)  评论(0编辑  收藏  举报