Balanced Lineup 【线段树】

版权声明:反正没人看 随意转载 https://blog.csdn.net/qq_38930523/article/details/83544081

题目链接POJ-3264

[kuangbin带你飞]专题七 线段树

题目描述

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.

思路

区间查询最大最小,可以用RMQ也可以用线段树;

代码

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

#define MAX 50050
#define INF 0x3f3f3f3f

struct Node{
    int l, r, Max, Min;
}tree[MAX * 4];

void push_up(int k)
{
    tree[k].Max = max(tree[k<<1].Max, tree[k<<1|1].Max);
    tree[k].Min = min(tree[k<<1].Min, tree[k<<1|1].Min);
}

void build(int k, int l, int r)
{
    tree[k].l = l, tree[k].r = r;
    if(l == r)
    {
        scanf("%d", &tree[k].Max);
        tree[k].Min = tree[k].Max;
    }
    else
    {
        int mid = (l + r) >> 1;
        build(k<<1, l, mid);
        build(k<<1|1, mid+1, r);
        push_up(k);
    }
}

int query_Max(int k, int l, int r)
{
    int L = tree[k].l, R = tree[k].r;
    if(l <= L && R <= r)
    {
        return tree[k].Max;
    }
    else
    {
        int tmp_max = -INF;
        int mid = (L + R) >> 1;
        if(l <= mid)
            tmp_max = max(tmp_max, query_Max(k<<1, l, r));
        if(mid < r)
            tmp_max = max(tmp_max, query_Max(k<<1|1, l, r));
        return tmp_max;
    }
}

int query_Min(int k, int l, int r)
{
    int L = tree[k].l, R = tree[k].r;
    if(l <= L && R <= r)
    {
        return tree[k].Min;
    }
    else
    {
        int tmp_min = INF;
        int mid = (L + R) >> 1;
        if(l <= mid)
            tmp_min = min(tmp_min, query_Min(k<<1, l, r));
        if(mid < r)
            tmp_min = min(tmp_min, query_Min(k<<1|1, l, r));
        return tmp_min;
    }
}

int main()
{
    int n, m;
    scanf("%d %d", &n, &m);
    build(1, 1, n);
    for(int i = 1; i<=m; i++)
    {
        int x, y;
        scanf("%d %d", &x, &y);
        printf("%d\n",query_Max(1, x, y) -  query_Min(1, x, y));
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_38930523/article/details/83544081