GSS1 - Can you answer these queries I
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.
这个题目可以用线段树去做,一个可行的思路就是计算出三个标记mc[](当前区间内最大的连续子串和),lc[](从当前区间左端点开始向右的最大的连续子串和),rc[](从当前区间右端点开始的向左的最大的连续子串和)。
查询的时候利用这三个标记进行计算就可以了。
#include<bits/stdc++.h>
#define MAXN 50010
using namespace std;
int lc[4*MAXN],rc[4*MAXN],mc[4*MAXN];
int prefix[MAXN];
void build(int id,int l,int r)
{
if(l==r)
{
mc[id]=lc[id]=rc[id]=prefix[l]-prefix[l-1];
return;
}
int mid=(l+r)/2;
build(id*2,l,mid);
build(id*2+1,mid+1,r);
lc[id]=max(lc[id*2],prefix[mid]-prefix[l-1]+lc[id*2+1]);
rc[id]=max(rc[id*2+1],prefix[r]-prefix[mid]+rc[id*2]);
mc[id]=max(max(mc[id*2],mc[id*2+1]),rc[id*2]+lc[id*2+1]);
}
int query(int id,int x,int y,int l,int r,int flag,int &ans)
{
if(l<=x&&y<=r)
{
ans=max(ans,mc[id]);
return flag==-1?lc[id]:rc[id];
}
int mid=(x+y)/2;
if(r<=mid)
return query(id*2,x,mid,l,r,-1,ans);
else if(l>mid)
return query(id*2+1,mid+1,y,l,r,1,ans);
else
{
int ln=query(id*2,x,mid,l,r,1,ans);
int rn=query(id*2+1,mid+1,y,l,r,-1,ans);
ans=max(ln+rn,ans);
if(flag==-1)
return max(lc[id*2],prefix[mid]-prefix[x-1]+rn);
else
return max(rc[id*2+1],prefix[y]-prefix[mid]+ln);
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
prefix[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&prefix[i]);
prefix[i]+=prefix[i-1];
}
build(1,1,n);
int m;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
int l,r;
scanf("%d%d",&l,&r);
int ans=prefix[l]-prefix[l-1];
query(1,1,n,l,r,-1,ans);
printf("%d\n",ans);
}
}
return 0;
}