cv3304 水果姐逛水果街Ⅰ(线段树)

题目链接

分析:
线性结构问题,可以用线段树解决
每个结点维护:
mx:区间最大值
mn:区间最小值
ls:从左向右走得到的最大差值
rs:从右向左走得到的最大差值

对于ls和rs的维护:
ans.ls=max(lc.ls,rc.ls,rc.mxlc.mn) a n s . l s = m a x ( l c . l s , r c . l s , r c . m x − l c . m n )
ans.rs=max(lc.rs,rc.rs,lc.mxrc.mn) a n s . r s = m a x ( l c . r s , r c . r s , l c . m x − r c . m n )

线段树区间询问即可

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

const int INF=1e9;
const int N=200005;
struct node{
    int x,y,mx,mn,ls,rs;
};
node t[N<<2],ans;
int n,m,a[N];

node update(node lc,node rc)
{
    node ans;
    ans.x=lc.x; ans.y=rc.y;

    ans.mx=max(lc.mx,rc.mx);
    ans.mn=min(lc.mn,rc.mn);

    ans.ls=max(max(lc.ls,rc.ls),rc.mx-lc.mn);
    ans.rs=max(max(lc.rs,rc.rs),lc.mx-rc.mn);

    return ans;
}

void build(int bh,int l,int r)
{
    t[bh].x=l; t[bh].y=r;
    if (l==r)
    {
        t[bh].mx=t[bh].mn=a[l];
        return;
    }
    int mid=(l+r)>>1;
    build(bh<<1,l,mid);
    build(bh<<1|1,mid+1,r);
    t[bh]=update(t[bh<<1],t[bh<<1|1]);
}

void ask(int bh,int l,int r,int x,int y)
{
    if (l>=x&&r<=y)
    {
        ans=update(ans,t[bh]);
        return;
    }
    int mid=(l+r)>>1;
    if (x<=mid) ask(bh<<1,l,mid,x,y);
    if (y>mid) ask(bh<<1|1,mid+1,r,x,y);
}

int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++) scanf("%d",&a[i]);
    build(1,1,n);
    scanf("%d",&m);
    for (int i=1;i<=m;i++)
    {
        int x,y,opt=0;
        scanf("%d%d",&x,&y);
        if (x==y) {
            printf("0\n");
            continue;
        } 
        if (x>y) opt=1,swap(x,y);

        ans.mn=INF; ans.mx=-INF; ans.rs=ans.ls=0;
        ask(1,1,n,x,y);
        if (opt) printf("%d\n",ans.rs);
        else printf("%d\n",ans.ls);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值