Cod sursa(job #1254239)

Utilizator rebound212Mihnea Savu rebound212 Data 2 noiembrie 2014 13:13:12
Problema SequenceQuery Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <algorithm>
#include <cstdio>
# define mij ((st+dr)>>1)
using namespace std;
struct arbore
{
    long long sum,best,st,dr;
};
arbore arb[400020],sol;
int n,m,v[400001],i,x,y;

inline arbore functie( arbore x, arbore y)
{

    if(x.best== -2000000000) return y;
    if(y.best== -2000000000) return x;
    arbore t;
    t.sum=x.sum+y.sum;
    t.best=max(x.dr+y.st, max(x.best,y.best));
    t.st=max(x.st, x.sum+y.st);
    t.dr=max(y.dr, y.sum+x.dr);
    return t;
}
inline void update (int nod, int st, int dr)
{

    if(st==dr)
    {
        arb[nod].st=v[st];
        arb[nod].dr=v[st];
        arb[nod].sum=v[st];
        arb[nod].best=v[st];
        return;
    }

    update(2*nod,st,mij);
    update(2*nod+1,mij+1,dr);
    arb[nod]=functie(arb[2*nod],arb[2*nod+1]);
}
inline arbore query (int nod, int st, int dr, int x, int y)
{ int mij;
    if(x<=st && dr<=y) return arb[nod];
    if(st!=dr)
    {

        arbore q1, q2;
        q1.best=q2.best= -2000000000;
        if(x<=mij) q1=query(nod*2,st,mij,x,y);
        if(y>mij) q2=query(nod*2+1,mij+1,dr,x,y);
        return functie(q1,q2);

    }
}

int main()
{
    freopen("sequencequery.in","r",stdin);
    freopen("sequencequery.out","w",stdout);
    scanf("%d %d\n",&n,&m);
    for(i=1; i<=n; i++)
    {
        scanf("%d",&v[i]);
    }

    update(1,1,n);
   while(m--)
    {

        scanf("%d %d\n",&x,&y);
        //if(x==y) printf("%d",v[x]);
       // else
       sol=query(1,1,n,x,y);
        printf("%lld\n",sol.best);
    }

    return 0;
}