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
题解:
#include<bits/stdc++.h>
using namespace std;
struct LNode
{
int l,r;
long long sum;
long long lsum;
long long rsum;
long long ans ;
}node[50007 * 4];
void push_up(int rt)
{
node[rt].sum = node[rt *2].sum + node[rt*2+1].sum;
node[rt].lsum = max(node[rt*2].lsum , node[rt*2].sum + node[rt*2+1].lsum);
node[rt].rsum = max(node[rt*2+1].rsum,node[rt*2+1].sum + node[rt*2].rsum);
node[rt].ans = node[rt*2].rsum + node[rt*2+1].lsum;
node[rt].ans = max(node[rt].ans, max(node[rt * 2].ans,node[rt * 2 +1].ans));
}
void build(int l,int r,int rt)
{
node[rt].l=l;
node[rt].r=r;
if(l==r)
{
scanf("%lld",&node[rt].sum);
node[rt].lsum=node[rt].rsum=node[rt].ans=node[rt].sum;
return ;
}
int mid=(l+r)/2;
build(l,mid,rt*2);
build(mid + 1,r,rt*2+1);
push_up(rt);
}
LNode getres(int l,int r,int rt)
{
if(node[rt].l == l && node[rt].r == r)
{
return node[rt];
}
int mid = (node[rt].l + node[rt].r)/2;
if(mid >= r)
{
return getres(l,r,rt*2);
}
else if(mid < l)
{
return getres(l,r,rt*2+1);
}
else
{
LNode res;
LNode lres,rres;
lres = getres(l,mid,rt*2);
rres = getres(mid+1,r,rt*2+1);
res.sum = lres.sum + rres.sum;
res.lsum = max(lres.lsum,lres.sum + rres.lsum);
res.rsum = max(rres.rsum,rres.sum + lres.rsum);
res.ans = max(lres.rsum + rres.lsum,max(lres.ans,rres.ans));
return res;
}
}
int main()
{
int n;
scanf("%d",&n);
build(1,n,1);
int k;
scanf("%d",&k);
while(k--)
{
int l,r;
scanf("%d%d",&l,&r);
if(l > r)
swap(l,r);
LNode res = getres(l,r,1);
printf("%lld\n",res.ans);
}
return 0;
}