Cod sursa(job #1254198)

Utilizator rebound212Mihnea Savu rebound212 Data 2 noiembrie 2014 12:20:37
Problema SequenceQuery Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <algorithm>
#include <cstdio>
using namespace std;
struct arbore
{
    int sum,best,st,dr;
};
arbore arb[400001];
int n,m,v[400001],i,x,y;

inline arbore functie( arbore x, arbore y)
{
    arbore t;
    if(x.best== -2000000000) return y;
    if(y.best==-2000000000) return x;
    t.sum=x.sum+y.sum;
    t.st=max(x.st,x.sum+y.st);
    t.dr=max(y.dr,y.sum+x.dr);
    t.best=max(y.st+x.dr,max(x.best,y.best));
    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;
    }
    int m=(st+dr)/2;
    update(2*nod,st,m);
    update(2*nod+1,m+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 m;
    if(st>=x && dr<=y) return arb[nod];
    if(st!=dr)
    {
        m=(st+dr)/2;
        arbore q1, q2;
        q1.best=q2.best= -2000000000;
        if(y>m) q1=query(nod*2+1,m+1,dr,x,y);
        if(x<m) q2=query(nod*2,st,m,x,y);
        return functie(q2,q1);

    }
}

int main()
{
    freopen("sequencequery.in","r",stdin);
    freopen("sequencequery.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(i=1; i<=n; i++)
    {
        scanf("%d",&v[i]);
    }
    update(1,1,n);
    for(i=1;i<=m;i++)
    {
        arbore sol;
        scanf("%d %d",&x,&y);
        if(x==y) printf("%d",v[x]);
        else
       {sol=query(1,1,n,x,y);
        printf("%d\n",sol.best);}
    }

    return 0;
}