Description
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
Input
Output
Sample Input
Sample Output
Hint
Added by: | |
Date: | 2006-11-01 |
Time limit: | 0.115s-0.230s |
Source limit: | 5000B |
Memory limit: | 1536MB |
Cluster: | |
Languages: | All except: ERL JS NODEJS PERL 6 VB.net |
小白逛公园的弱化版,写一下练手,第一次因为没有写return wa了。
#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
const int N=50005;
int n,m;
long long data[N];
struct node
{
int l,r;
long long sum,tot,lm,rm;
}a[4*N];
void build(int num,int l,int r)
{
a[num].l=l,a[num].r=r;
if(l==r)
{
a[num].sum=a[num].tot=a[num].lm=a[num].rm=data[l];
return ;
}
int mid=(l+r)/2;
build(2*num,l,mid);
build(2*num+1,mid+1,r);
a[num].sum=a[2*num].sum+a[2*num+1].sum;
a[num].lm=max(a[2*num].lm,a[2*num].sum+a[2*num+1].lm);
a[num].rm=max(a[2*num+1].rm,a[2*num+1].sum+a[2*num].rm);
a[num].tot=max(max(a[2*num].tot,a[2*num+1].tot),a[2*num].rm+a[2*num+1].lm);
}
node query(int num,int l,int r)
{
if(a[num].l>=l&&a[num].r<=r)
return a[num];
if(a[2*num].r>=r)
return query(2*num,l,r);
if(a[2*num+1].l<=l)
return query(2*num+1,l,r);
node u1,u2,res;
u1=query(2*num,l,r);
u2=query(2*num+1,l,r);
res.sum=u1.sum+u2.sum;
res.lm=max(u1.lm,u1.sum+u2.lm);
res.rm=max(u2.rm,u2.sum+u1.rm);
res.tot=max(max(u1.tot,u2.tot),u1.rm+u2.lm);
return res;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&data[i]);
build(1,1,n);
scanf("%d",&m);
int x,y;
while(m--)
{
scanf("%d%d",&x,&y);
printf("%lld\n",query(1,x,y).tot);
}
return 0;
}