水果姐逛水果街Ⅰ(codevs 3304)

时间:2023-03-09 22:19:45
水果姐逛水果街Ⅰ(codevs 3304)
题目描述 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

/*
对于每个区间,维护它的最小值,最大值,从左向右的最大收益,从右向左的最大收益
一个区间内的最大收益=max(左孩子最大收益,右孩子最大收益,右孩子最大值-左孩子最小值)
*/
#include<iostream>
#include<cstdio>
#define lson l,m,now*2
#define rson m+1,r,now*2+1
#define M 800010
using namespace std;
int mx[M],mn[M],lmax[M],rmax[M],a[M/];
int tot;
void push_up(int now)
{
mx[now]=max(mx[now*],mx[now*+]);
mn[now]=min(mn[now*],mn[now*+]);
lmax[now]=max(max(lmax[now*],lmax[now*+]),mx[now*+]-mn[now*]);
rmax[now]=max(max(rmax[now*],rmax[now*+]),mx[now*]-mn[now*+]);
} void build(int l,int r,int now)
{
if(l==r)
{
mx[now]=mn[now]=a[l];
return;
}
int m=(l+r)/;
build(lson);
build(rson);
push_up(now);
} int get_max(int x,int y,int l,int r,int now)
{
if (x<=l&& y>=r) return mx[now];
int m = (l+r)/;
if (x>m) return get_max(x,y,rson);
else if (y<=m) return get_max(x,y,lson);
else return max(get_max(m+,y,rson),get_max(x,m,lson));
} int get_min(int x,int y,int l,int r,int now)
{
if (x<=l&& y>=r) return mn[now];
int m = (l+r)/;
if (x>m) return get_min(x,y,rson);
else if (y<=m) return get_min(x,y,lson);
else return min(get_min(m+,y,rson),get_min(x,m,lson));
} int query_l(int x,int y,int l,int r,int now)
{
int m=(l+r)/;
if (x<=l&& y>=r) return lmax[now];
if (y<=m) return query_l(x,y,lson);
else if (x>m) return query_l(x,y,rson);
else
{
int temp = ;
temp=max(query_l(x,y,lson),query_l(x,y,rson));
temp=max(temp,get_max(x,y,rson)-get_min(x,y,lson));
return temp;
}
}
int query_r(int x,int y,int l,int r,int now)
{
int m=(l+r)/;
if (x<=l&& y>=r) return rmax[now];
if (y<=m) return query_r(x,y,lson);
else if (x>m) return query_r(x,y,rson);
else
{
int temp = ;
temp=max(query_r(x,m,lson),query_r(x,y,rson));
temp=max(temp,get_max(x,y,lson)-get_min(x,y,rson));
return temp;
}
}
int main()
{
int n,m,l,r;
scanf("%d",&n);
for (int i=;i<=n;i++) scanf("%d",&a[i]);
build(,n,);
scanf("%d",&m);
for (int i=;i<=m;i++)
{
scanf("%d%d",&l,&r);
if (l<r) printf("%d\n",query_l(l,r,,n,));
else printf("%d\n",query_r(r,l,,n,));
}
}