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
注意:线段树用
if(r<=mid)
else if(l>mid)
else
来判断的话,前面必须是if(lt[x].l&&rt[x].r)而不是if(l<=t[x].l&&t[x].r<=r)
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
typedef double db;
typedef long long ll;
#define rep(i,s,t) for(int i=s;i<=t;i++)
#define per(i,s,t) for(int i=s;i>=t;i--)
#define ms0(ar) memset(ar,0,sizeof ar)
#define ms1(ar) memset(ar,-1,sizeof ar)
#define lson x<<1
#define rson x<<1|1
const int N=5e4+5;
struct tr{
int l,r,p,lp,rp;
}t[N<<2];
int a[N],s[N];
void build(int x,int l,int r){
t[x].l=l,t[x].r=r;
if(l==r){
t[x].p=t[x].lp=t[x].rp=a[l];
return;
}
int mid=(l+r)>>1;
build(lson,l,mid);
build(rson,mid+1,r);
t[x].rp=max(t[lson].rp+s[t[rson].r]-s[t[rson].l-1],t[rson].rp);
t[x].lp=max(t[rson].lp+s[t[lson].r]-s[t[lson].l-1],t[lson].lp);
t[x].p=max(t[lson].p,t[rson].p);
t[x].p=max(t[rson].lp+t[lson].rp,t[x].p);
}
int ql(int x,int l,int r){
if(t[x].r<l) return 0;
if(t[x].l==l&&t[x].r==r) return t[x].rp;
int mid=(t[x].l+t[x].r)>>1;
if(r<=mid) return ql(lson,l,r);
else if(l>mid) return ql(rson,l,r);
else return max(ql(rson,mid+1,r),max(s[r]-s[mid],s[r]-s[mid]+ql(lson,l,mid)));
}
int qr(int x,int l,int r){
if(t[x].l>r) return 0;
if(t[x].l==l&&t[x].r==r) return t[x].lp;
int mid=(t[x].l+t[x].r)>>1;
if(r<=mid) return qr(lson,l,r);
else if(l>mid) return qr(rson,l,r);
else return max(qr(lson,l,mid),max(s[mid]-s[l-1],s[mid]-s[l-1]+qr(rson,mid+1,r)));
}
int query(int x,int l,int r){
if(t[x].l>r||t[x].r<l) return 0;
if(l==t[x].l&&t[x].r==r) return t[x].p;
int mid=(t[x].l+t[x].r)>>1,ans;
if(r<=mid) ans=query(lson,l,r);
else if(l>mid) ans=query(rson,l,r);
else{
ans=max(query(lson,l,mid),query(rson,mid+1,r));
ans=max(ans,ql(lson,l,mid)+qr(rson,mid+1,r));
}
return ans;
}
int main(){
int n,m,l,r;
cin>>n;
rep(i,1,n){
cin>>a[i];
s[i]=s[i-1]+a[i];
}
build(1,1,n);
cin>>m;
rep(i,1,m){
cin>>l>>r;
printf("%d\n",query(1,l,r));
}
return 0;
}