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
思路:
最主要的是如何求最大区间和,在这里我在树里(结构体)设了lans(从最左边开始的最大和),rans(最右边),ans(整个区间的最大和)。
关键看pushup()以及query()中的else{},理解清楚了就会了。
#include<iostream>
using namespace std;
const int N=50000;
int n,m,x,y,ans;
int a[N+5];
struct tree
{
int sum,lans,rans,ans;
}t[N*4+5];
void pushup(int k)
{
t[k].sum =t[k*2].sum +t[k*2+1].sum ;
t[k].lans =max(t[k*2].lans ,t[k*2].sum +t[k*2+1].lans );
t[k].rans =max(t[k*2+1].rans ,t[k*2+1].sum +t[k*2].rans );
t[k].ans =max(max(t[k*2].ans ,t[k*2+1].ans ),t[k*2].rans +t[k*2+1].lans );
}
void build(int k,int l,int r)
{
if(l==r)
{
t[k].sum =t[k].ans =t[k].lans =t[k].rans =a[l];
return;
}
int mid=(l+r)/2;
build(k*2,l,mid);
build(k*2+1,mid+1,r);
pushup(k);
}
tree query(int k,int x,int y,int l,int r)
{
if(l>=x&&r<=y)
return t[k] ;
int mid=(l+r)/2;
if(y<=mid)
return query(k*2,x,y,l,mid);
else if(x>mid)
return query(k*2+1,x,y,mid+1,r);
else
{
tree left,right,re;
left=query(k*2,x,y,l,mid);
right=query(k*2+1,x,y,mid+1,r);
re.sum =left.sum +right.sum ;
re.lans =max(left.lans ,left.sum +right.lans );
re.rans =max(right.rans ,right.sum +left.rans );
re.ans =max(max(left.ans ,right.ans ),left.rans +right.lans );
return re;
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
scanf("%d",&m);
while(m--)
{
scanf("%d %d",&x,&y);
ans=query(1,x,y,1,n).ans ;
printf("%d\n",ans);
}
return 0;
}