You are given a sequence

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

/*************************************************************************
 > File Name: spojgss1.cpp
 > Author: Henry Chen
 > Mail: 390989083@qq.com 
 > Created Time: 六  9/19 22:03:14 2020
 ************************************************************************/

#include<bits/stdc++.h>
using namespace std;
long long a[50005];
struct Node
{
 long long l,r;
 long long lmax,rmax,mx;
 long long sum;
}tr[200005],as[200005];
long long tot = 0;
void build(long long rt,long long l,long long r)
{
 if(l == r)
 {
  tr[rt] = (Node){l,r,a[l],a[l],a[l],a[l]};
  return;
 }
 long long mid = (l+r)/2;
 tr[rt].l = l;
 tr[rt].r = r;
 long long ls = rt*2;
 long long rs = rt*2+1;
 build(ls,l,mid);
 build(rs,mid+1,r);
 tr[rt].sum = tr[ls].sum + tr[rs].sum;
 tr[rt].lmax = max(tr[ls].lmax,tr[rs].lmax+tr[ls].sum);
 tr[rt].rmax = max(tr[rs].rmax,tr[rs].sum+tr[ls].rmax);
 tr[rt].mx = max(max(tr[rs].mx,tr[ls].mx),tr[ls].rmax+tr[rs].lmax);
}
void ask(long long rt,long long l,long long r,long long u,long long v)
{
 if(l >= u && r <= v)
 {
  as[rt] = tr[rt];
  return;
 }
 long long mid = (l+r)/2;
 if(mid >= u)
 {
  ask(rt*2,l,mid,u,v);
 }
 else
 {
  as[rt*2] = (Node){l,mid,-1000000000,-1000000000,-1000000000,0};
 }
 if(mid+1 <= v)
 {
  ask(rt*2+1,mid+1,r,u,v);
 }
 else
 {
  as[rt*2+1] = (Node){mid+1,r,-1000000000,-1000000000,-1000000000,0};
 }
 long long ls = rt*2;
 long long rs = rt*2+1;
 as[rt].sum = as[ls].sum + as[rs].sum;
 as[rt].lmax = max(as[ls].lmax,as[rs].lmax+as[ls].sum);
 as[rt].rmax = max(as[rs].rmax,as[rs].sum+as[ls].rmax);
 as[rt].mx = max(max(as[rs].mx,as[ls].mx),as[ls].rmax+as[rs].lmax); 
}
int main()
{
 long long n;
 cin >> n;
 for(long long i = 1;i <= n;i++)
 {
  scanf("%lld",&a[i]);
 }
 build(1,1,n);
 long long m;
 cin >> m;
 for(long long i = 1;i <= m;i++)
 {
  long long l,r;
  scanf("%lld%lld",&l,&r);
  ask(1,1,n,l,r);
  printf("%lld
",as[1].mx);
 }
 return 0;
}
原文地址:https://www.cnblogs.com/mzyy1001/p/13703069.html