SP1043 GSS1 - Can you answer these queries I

#include<bits/stdc++.h>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
int n,m,a[500005];
struct Tree{
    LL l,r,ls,rs,mx,sum;
}tre[500005<<2];
void build(int rt,int L,int R)
{ 
    if(L==R)
    {
        tre[rt].sum=tre[rt].mx=tre[rt].ls=tre[rt].rs=a[L];////////ls->l
        tre[rt].l=tre[rt].r=R;
        return ;
    }
    int mid=(L+R)>>1;
    build(rt<<1,L,mid);
    build(rt<<1|1,mid+1,R); 
    tre[rt].l=tre[rt<<1].l;
    tre[rt].r=tre[rt<<1|1].r;
    tre[rt].sum=tre[rt<<1].sum+tre[rt<<1|1].sum;
    tre[rt].mx=max(tre[rt<<1].rs+tre[rt<<1|1].ls,max(tre[rt<<1].mx,tre[rt<<1|1].mx));///////mx->ls,tre[rt<<1].ls
    tre[rt].ls=max(tre[rt<<1].ls,tre[rt<<1].sum+tre[rt<<1|1].ls);
    tre[rt].rs=max(tre[rt<<1|1].rs,tre[rt<<1|1].sum+tre[rt<<1].rs);
}
Tree query(int rt,int L,int R)
{
    if(L<=tre[rt].l && R>=tre[rt].r) return tre[rt];    
    int mid=(tre[rt].l+tre[rt].r)>>1;
    if(L>mid) return query(rt<<1|1,L,R);
    if(R<=mid) return query(rt<<1,L,R);
    Tree ans,x,y;
    x=query(rt<<1,L,R); 
    y=query(rt<<1|1,L,R);
    ans.sum=x.sum +y.sum;
    ans.mx=max(max(x.mx,y.mx),x.rs+y.ls);//没有写max 
    ans.ls =max(x.ls,x.sum+y.ls);
    ans.rs =max(y.rs,y.sum+x.rs);
    return ans; 
} 
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    build(1,1,n);
//  for(int i=1;i<=2*n;i++)
//      cout<<i<<","<<tre[i].sum<<","<<tre[i].l<<","<<tre[i].r<<endl;
    scanf("%d",&m);
    while(m--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%lld\n",query(1,x,y).mx);   
    } 
}

猜你喜欢

转载自blog.csdn.net/yjeannette/article/details/81105602
今日推荐