POJ 3264 Balanced Lineup

本文介绍了一种利用线段树解决区间查询问题的方法,通过构建两个线段树分别维护最大值和最小值,高效地实现了区间内最大值与最小值之差的查询。

题意:给出n个数,q次询问,每次询问一段区间输出区间内最大值和最小值的差。

 

解法:线段树。拿两个线段树分别维护最大值和最小值。

 

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int maxn = 50005;
int Max[maxn << 2], Min[maxn << 2];
int a[maxn];
void pushUpMax(int rt)
{
    Max[rt] = max(Max[rt << 1], Max[rt << 1 | 1]);
}
void buildMax(int l, int r, int rt)
{
    if(l == r)
    {
        Max[rt] = a[l];
        return ;
    }
    int m = (l + r) >> 1;
    buildMax(lson);
    buildMax(rson);
    pushUpMax(rt);
}
void pushUpMin(int rt)
{
    Min[rt] = min(Min[rt << 1], Min[rt << 1 | 1]);
}
void buildMin(int l, int r, int rt)
{
    if(l == r)
    {
        Min[rt] = a[l];
        return ;
    }
    int m = (l + r) >> 1;
    buildMin(lson);
    buildMin(rson);
    pushUpMin(rt);
}
int queryMax(int ll, int rr, int l, int r, int rt)
{
    if(ll <= l && rr >= r)
        return Max[rt];
    int m = (l + r) >> 1;
    int res = INT_MIN;
    if(ll <= m)
        res = max(res, queryMax(ll, rr, lson));
    if(rr > m)
        res = max(res, queryMax(ll, rr, rson));
    return res;
}
int queryMin(int ll, int rr, int l, int r, int rt)
{
    if(ll <= l && rr >= r)
        return Min[rt];
    int m = (l + r) >> 1;
    int res = INT_MAX;
    if(ll <= m)
        res = min(res, queryMin(ll, rr, lson));
    if(rr > m)
        res = min(res, queryMin(ll, rr, rson));
    return res;
}
int main()
{
    int n, q;
    while(~scanf("%d%d", &n, &q))
    {
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        buildMax(1, n, 1);
        buildMin(1, n, 1);
        for(int i = 0; i < q; i++)
        {
            int maxx, minn;
            int l, r;
            scanf("%d%d", &l, &r);
            maxx = queryMax(l, r, 1, n, 1);
            minn = queryMin(l, r, 1, n, 1);
            printf("%d\n", maxx - minn);
        }
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/Apro/p/4477509.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值