Can you answer these queries I
You are given a sequence A[1], A[2], ..., A[N] . ( |A[i]| ≤ 15007 , 1 ≤ N ≤ 50000 ). A query is defined as follows:
Query(x,y) = Max { a[i]+a[i+1]+...+a[j] ; x ≤ i ≤ j ≤ y }.
Given M queries, your program must output the results of these queries.
Input
- The first line of the input file contains the integer N.
- In the second line, N numbers follow.
- The third line contains the integer M.
- M lines follow, where line i contains 2 numbers xi and yi.
Output
Your program should output the results of the M queries, one query per line.
Example
Input: 3 -1 2 3 1 1 2 Output: 2
每个区间维护区间和sum,区间最大字段和maxs,区间最大前缀和maxl,区间最大后缀和maxr。则合并区间时,可得关系如下
void pushup(int rt)
{
a[rt].sum=a[2*rt].sum+a[2*rt+1].sum;
a[rt].maxl=max(a[2*rt].maxl,a[2*rt].sum+a[2*rt+1].maxl);
a[rt].maxr=max(a[2*rt+1].maxr,a[2*rt+1].sum+a[2*rt].maxr);
a[rt].maxs=max(max(a[2*rt].maxs,a[2*rt+1].maxs),a[2*rt].maxr+a[2*rt+1].maxl);
}
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=5e4+10;
const ll inf=1e18;
int n,m;
ll p;
struct node
{
ll sum,maxs,maxl,maxr;
}a[maxn<<2];
void pushup(int rt)
{
a[rt].sum=a[2*rt].sum+a[2*rt+1].sum;
a[rt].maxl=max(a[2*rt].maxl,a[2*rt].sum+a[2*rt+1].maxl);
a[rt].maxr=max(a[2*rt+1].maxr,a[2*rt+1].sum+a[2*rt].maxr);
a[rt].maxs=max(max(a[2*rt].maxs,a[2*rt+1].maxs),a[2*rt].maxr+a[2*rt+1].maxl);
}
void build(int l,int r,int rt)
{
if(l==r)
{
scanf("%lld",&p);
a[rt].sum=a[rt].maxs=a[rt].maxl=a[rt].maxr=p;
return;
}
int mid=(l+r)/2;
build(l,mid,2*rt);
build(mid+1,r,2*rt+1);
pushup(rt);
}
node query(int x,int y,int l,int r,int rt)
{
if(x<=l&&y>=r)
{
return a[rt];
}
int mid=(l+r)/2;
node L,R,S;
L.sum=L.maxs=L.maxl=L.maxr=-inf;
R.sum=R.maxs=R.maxl=R.maxr=-inf;
S.sum=S.maxs=S.maxl=S.maxr=0;
if(x<=mid)
{
L=query(x,y,l,mid,2*rt);
S.sum+=L.sum;
}
if(y>mid)
{
R=query(x,y,mid+1,r,2*rt+1);
S.sum+=R.sum;
}
S.maxl=max(L.maxl,L.sum+R.maxl);
S.maxr=max(R.maxr,R.sum+L.maxr);
S.maxs=max(max(L.maxs,R.maxs),L.maxr+R.maxl);
return S;
}
int main()
{
scanf("%d",&n);
build(1,n,1);
scanf("%d",&m);
int x,y;
while(m--)
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(x,y,1,n,1).maxs);
}
return 0;
}