Can you answer these queries V gss5

在gss3的基础上再YY一下吧~~~

http://www.spoj.pl/problems/GSS5/

View Code
#include<stdio.h>
#include<string.h>
#include<iostream>
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
const int maxn = 10005;
int sum[maxn],bs[maxn];
int n,m;
struct nd{
    int sum,lx,rx,mx;
}as[maxn<<2];
inline void pushUp(int rt)
{
    as[rt].lx = max(as[lson].lx,as[lson].sum+as[rson].lx);
    as[rt].rx = max(as[rson].rx,as[rson].sum+as[lson].rx);
    as[rt].mx = max(max(as[lson].mx,as[rson].mx),as[lson].rx+as[rson].lx);
    as[rt].sum = as[lson].sum + as[rson].sum;
}
void build(int rt,int l,int r)
{
    int md = (l + r) >> 1;
    if(l==r){
        as[rt].lx = as[rt].rx = as[rt].mx = as[rt].sum = bs[l];
        return;
    }
    build(lson,l,md);
    build(rson,md+1,r);
    pushUp(rt);
}
int queryR(int rt,int l,int r,int L,int R)
{
    int md = (l + r) >> 1;
    if(L>R)return 0;
    if(l==L&&r==R)return as[rt].rx;
    if(R<=md)return queryR(lson,l,md,L,R);
    if(L>md)return queryR(rson,md+1,r,L,R);
    return max(queryR(rson,md+1,r,md+1,R),max(sum[R]-sum[md],sum[R]-sum[md]+queryR(lson,l,md,L,md)));
}
int queryL(int rt,int l,int r,int L,int R)
{
    int md = (l + r) >> 1;
    if(L>R)return 0;
    if(l==L&&r==R)return as[rt].lx;
    if(R<=md)return queryL(lson,l,md,L,R);
    if(L>md)return queryL(rson,md+1,r,L,R);
    return max(queryL(lson,l,md,L,md),max(sum[md]-sum[L-1],sum[md]-sum[L-1]+queryL(rson,md+1,r,md+1,R)));
}
int query(int rt,int l,int r,int L,int R)
{
    int md = (l + r) >> 1;
    if(L>R)return 0;
    if(l==L&&r==R)return as[rt].mx;
    if(R<=md)return query(lson,l,md,L,R);
    if(L>md)return query(rson,md+1,r,L,R);
    return max(max(query(lson,l,md,L,md),query(rson,md+1,r,md+1,R)),queryR(lson,l,md,L,md)+queryL(rson,md+1,r,md+1,R));
}
int main()
{
    int T,x1,x2,y1,y2,ans;
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        for(int i = 1; i <= n; ++ i){
            scanf("%d",bs+i);
            sum[i]=sum[i-1]+bs[i];
        }
        build(1,1,n);
        scanf("%d",&m);
        while(m--){
            scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
            if(x2>y1) ans=sum[x2-1]-sum[y1]+queryL(1,1,n,x2,y2)+queryR(1,1,n,x1,y1);
            else if(y1>=y2) ans=max(query(1,1,n,x2,y2),queryL(1,1,n,x2,y2)+queryR(1,1,n,x1,x2-1));
            else{
                ans=max(query(1,1,n,x2,y1),max(queryR(1,1,n,x1,x2-1)+queryL(1,1,n,x2,y1),max(queryR(1,1,n,x2,y1)+queryL(1,1,n,y1+1,y2),queryR(1,1,n,x1,x2-1)+queryL(1,1,n,y1+1,y2)+sum[y1]-sum[x2-1])));
            }
            printf("%d\n",ans);
        }
    }
    return 0;
}

posted on 2012-09-30 11:29  aigoruan  阅读(176)  评论(0)    收藏  举报

导航