【线段树求区间最大连续子段和】 SPOJ - GSS1 Can you answer these queries I

 

Can you answer these queries I

 SPOJ - GSS1 

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

每个区间维护区间和sum,区间最大字段和maxs,区间最大前缀和maxl,区间最大后缀和maxr。则合并区间时,可得关系如下 
 

void pushup(int rt)
{
    a[rt].sum=a[2*rt].sum+a[2*rt+1].sum;
    a[rt].maxl=max(a[2*rt].maxl,a[2*rt].sum+a[2*rt+1].maxl);
    a[rt].maxr=max(a[2*rt+1].maxr,a[2*rt+1].sum+a[2*rt].maxr);
    a[rt].maxs=max(max(a[2*rt].maxs,a[2*rt+1].maxs),a[2*rt].maxr+a[2*rt+1].maxl);
}

 

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn=5e4+10;
const ll inf=1e18;
int n,m;
ll p;
struct node
{
    ll sum,maxs,maxl,maxr;
}a[maxn<<2];

void pushup(int rt)
{
    a[rt].sum=a[2*rt].sum+a[2*rt+1].sum;
    a[rt].maxl=max(a[2*rt].maxl,a[2*rt].sum+a[2*rt+1].maxl);
    a[rt].maxr=max(a[2*rt+1].maxr,a[2*rt+1].sum+a[2*rt].maxr);
    a[rt].maxs=max(max(a[2*rt].maxs,a[2*rt+1].maxs),a[2*rt].maxr+a[2*rt+1].maxl);
}

void build(int l,int r,int rt)
{
    if(l==r)
    {
        scanf("%lld",&p);
        a[rt].sum=a[rt].maxs=a[rt].maxl=a[rt].maxr=p;
        return;
    }
    int mid=(l+r)/2;
    build(l,mid,2*rt);
    build(mid+1,r,2*rt+1);
    pushup(rt);
}

node query(int x,int y,int l,int r,int rt)
{
    if(x<=l&&y>=r)
    {
        return a[rt];
    }
    int mid=(l+r)/2;
    node L,R,S;
    L.sum=L.maxs=L.maxl=L.maxr=-inf;
    R.sum=R.maxs=R.maxl=R.maxr=-inf;
    S.sum=S.maxs=S.maxl=S.maxr=0;
    if(x<=mid)
    {
        L=query(x,y,l,mid,2*rt);
        S.sum+=L.sum;
    }
    if(y>mid)
    {
        R=query(x,y,mid+1,r,2*rt+1);
        S.sum+=R.sum;
    }
    S.maxl=max(L.maxl,L.sum+R.maxl);
    S.maxr=max(R.maxr,R.sum+L.maxr);
    S.maxs=max(max(L.maxs,R.maxs),L.maxr+R.maxl);
    return S;
}

int main()
{
    scanf("%d",&n);
    build(1,n,1);
    scanf("%d",&m);
    int x,y;
    while(m--)
    {
        scanf("%d%d",&x,&y);
        printf("%lld\n",query(x,y,1,n,1).maxs);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值