【线段树】【分类讨论】水果姐逛水果街Ⅰ

3304 水果姐逛水果街Ⅰ

时间限制: 2 s
空间限制: 256000 KB
题目等级 : 钻石 Diamond

题目描述 Description

水果姐今天心情不错,来到了水果街。
水果街有n家水果店,呈直线结构,编号为1~n,每家店能买水果也能卖水果,并且同一家店卖与买的价格一样。
学过oi的水果姐迅速发现了一个赚钱的方法:在某家水果店买一个水果,再到另外一家店卖出去,赚差价。
就在水果姐窃喜的时候,cgh突然出现,他为了为难水果姐,给出m个问题,每个问题要求水果姐从第x家店出发到第y家店,途中只能选一家店买一个水果,然后选一家店(可以是同一家店,但不能往回走)卖出去,求每个问题中最多可以赚多少钱。

输入描述 Input Description

第一行n,表示有n家店
下来n个正整数,表示每家店一个苹果的价格。
下来一个整数m,表示下来有m个询问。
下来有m行,每行两个整数x和y,表示从第x家店出发到第y家店。

输出描述 Output Description

有m行。
每行对应一个询问,一个整数,表示面对cgh的每次询问,水果姐最多可以赚到多少钱。

样例输入 Sample Input

10
2 8 15 1 10 5 19 19 3 5 
4
6 6
2 8
2 2
6 3

样例输出 Sample Output

0
18
0
14

数据范围及提示 Data Size & Hint

0<=苹果的价格<=10^8
0<n,m<=200000

题解:

显而易见的线段树。维护一下区间最大值、最小值,从前向后走的最大差值,和从后向前的最大差值。只是在查询的时候需要分类讨论一下,有点恶心。。

Code:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define root 1,1,n
#define lchild rt<<1,l,m
#define rchild rt<<1|1,m+1,r
using namespace std;
struct Tree{
    int maxn,minn,chaq,chah;
}tree[1000010];
int n,q;
int in(){
    int x=0; char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
    return x;
}
void push_up(int rt){
    tree[rt].maxn=max(tree[rt<<1].maxn,tree[rt<<1|1].maxn);
    tree[rt].minn=min(tree[rt<<1].minn,tree[rt<<1|1].minn);
    int q=tree[rt<<1].maxn-tree[rt<<1|1].minn,h=tree[rt<<1|1].maxn-tree[rt<<1].minn;
    tree[rt].chaq=max(q,max(tree[rt<<1].chaq,tree[rt<<1|1].chaq));
    tree[rt].chah=max(h,max(tree[rt<<1].chah,tree[rt<<1|1].chah));
}
void build(int rt,int l,int r){
    if (l==r){
        tree[rt].maxn=tree[rt].minn=in();
        tree[rt].chaq=tree[rt].chah=0;
        return;
    }
    int m=(l+r)>>1;
    build(lchild); build(rchild);
    push_up(rt);
}
Tree query(int rt,int l,int r,int ll,int rr){
    if (ll<=l && r<=rr) return (Tree)tree[rt];
    int m=(l+r)>>1; Tree s1,s2,s3;
    s1=s2=s3=(Tree){0,0x7fffffff,0,0};
    if (ll<=m) s1=(Tree)query(lchild,ll,rr);
    if (rr>m) s2=(Tree)query(rchild,ll,rr);
    s3.maxn=max(s1.maxn,s2.maxn); s3.minn=min(s1.minn,s2.minn);
    s3.chaq=max(max(s1.chaq,s2.chaq),s1.maxn-s2.minn);
    s3.chah=max(max(s1.chah,s2.chah),s2.maxn-s1.minn);
    return s3;
}
int main(){
    n=in();
    build(root);
    q=in();
    while (q--){
        int x=in(),y=in(),ans;
        if (x==y) ans=0;
        else if (x<y) ans=query(root,x,y).chah;
        else ans=query(root,y,x).chaq;
        printf("%d\n",ans);
    }
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值