线段树求区间最大值与最小值的差

本文介绍如何利用线段树数据结构解决区间内最大值与最小值差值的问题,详细阐述了线段树的构建和更新过程,并通过POJ 3264题实例进行解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://poj.org/problem?id=3264

#include <cmath>
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define L(x) (x << 1)
#define R(x) (x << 1 | 1)
#define INT_MAX 0x7fffffff
const int MAX = 50010;
struct Tnode
{
    int mmax,mmin,val;
    int l,r;
};
Tnode node[MAX*3];
int v[MAX],big,small;
void init()
{
    memset(node,0,sizeof(node));
}
void build(int t,int l,int r)
{
    node[t].l=l;
    node[t].r=r;
    if(l==r-1)
    {
        node[t].mmin=v[l];
        node[t].mmax=v[l];
        return ;
    }
    int mid =(l+r)>>1;
    build(L(t),l,mid);
    build(R(t),mid,r);
    node[t].mmax=max(node[L(t)].mmax,node[R(t)].mmax);
    node[t].mmin=min(node[L(t)].mmin,node[R(t)].mmin);
}
void get(int t,int l,int r)
{
    if(node[t].l==l&&node[t].r==r)
    {
        big=max(node[t].mmax,big);
        small=min(node[t].mmin,small);
        return ;
    }
    int mid=(node[t].l+node[t].r)>>1;
    if(l>=mid)
         get(R(t),l,r);
    else if(r<=mid)
         get(L(t),l,r);
    else
    {
        get(R(t),mid,r);
        get(L(t),l,mid);
    }
}
int main()
{
    int n,m,x,y;
    while( ~scanf("%d%d",&n,&m))
    {
        init();
        for(int i=1; i<=n; i++)
            scanf("%d",&v[i]);
        build(1,1,n+1);
        while(m--)
        {
            scanf("%d%d",&x,&y);
            small=INT_MAX; big=0;
            get(1,x,y+1);
            printf("%d\n",big-small);
        }
    }
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值