[NWPU][2014][TRN][13]线段树第一讲 B - 基础 POJ 3264

来源:互联网 发布:医疗大数据应用案例 编辑:程序博客网 时间:2024/05/29 15:28
B - 基础
Time Limit:5000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 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.. NQ+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

#include<iostream>#include<cstdio>using namespace std;const int MAXN = 50005;int h[50005], MAX, MIN;struct node{    int l, r;    int MAX, MIN;}tree[MAXN * 4];void build(int p, int l, int r){    tree[p].l = l;    tree[p].r = r;    if(l ==r) {tree[p].MAX = tree[p].MIN = h[l]; return ; }    int mid = (l + r) / 2;    build(p * 2, l, mid);    build(p * 2 + 1, mid + 1, r);    //tree[p] = tree[p * 2] + tree[p * 2 + 1];    tree[p].MAX = max(tree[p * 2].MAX, tree[p * 2 + 1].MAX);    tree[p].MIN = min(tree[p * 2].MIN, tree[p * 2 + 1].MIN );}void find(int l, int r, int p){    if(tree[p].l == l && tree[p].r == r)    {        MAX = max(MAX, tree[p].MAX);        MIN = min(MIN, tree[p].MIN);        return ;    }    int mid = (tree[p].r + tree[p].l) / 2;    if(mid >= r) find(l, r, p * 2);    else if(mid < l) find(l, r, p * 2 + 1);    else    {        find(l, mid, p * 2);        find(mid + 1, r, p * 2 + 1);    }}int main(){    int n, p;    //cin >> n >> p;    scanf("%d%d", &n, &p);    for(int i = 1; i <= n; i++)    {        //cin >> h[i];        scanf("%d", &h[i]);    }    build(1, 1, n);    int x, y;    while(p--)    {        //cin >> x >> y;        scanf("%d%d", &x, &y);        MAX = -0xfffff;        MIN = 0xfffff;        find(x, y, 1);        //cout << MAX - MIN  << endl;        printf("%d\n", MAX - MIN);    }    return 0;}


0 0
原创粉丝点击