Cod sursa(job #2879026)

Utilizator Alle43221Moroz Alexandra-Ioana Alle43221 Data 28 martie 2022 11:03:45
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <iostream>
#include <fstream>

#define max_n 100002

using namespace std;

ifstream fin("sequencequery.in");
ofstream fout("sequencequery.out");

int v[max_n], n, m, a, b;

struct nod
{
    long long s;
    long long ssec;
    long long first, last;
} A[4*max_n];

nod update (nod a, nod b)
{
    nod aux;
    aux.s=a.s+b.s;
    aux.first=max(a.first, b.first+a.s);
    aux.last=max(b.last, a.last+b.s);
    aux.ssec=max(a.last+b.first, max(a.ssec, b.ssec));
    return aux;
}

void build(int l, int r, int n)
{
    if(r==l)
    {
        A[n].s=v[l];
        A[n].ssec=v[l];
        A[n].first=v[l];
        A[n].last=v[l];
    }
    else
    {
        int m=(l+r)/2;
        build(l, m, 2*n);
        build(m+1, r, 2*n+1);
        A[n]=update(A[2*n], A[2*n+1]);
    }
}

nod maximul(int l, int r, int n, int a, int b)
{
    if((a<=l)&&(r<=b))
    {
        return A[n];
    }
    else
    {
        int m=(l+r)/2;

        if(m>=b)
        {
            return maximul(l, m, 2*n, a, b);
        }
        if(m+1<=a)
        {
            return maximul(m+1, r, 2*n+1, a, b);
        }
        nod s, d;
        s=maximul(l, m, 2*n, a, b);
        d=maximul(m+1, r, 2*n+1, a, b);
        return update(s, d);
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=n; i++)
    {
        fin>>v[i];
    }
    build(1, n, 1);

    for(int i=0; i<m; i++)
    {
        fin>>a>>b;
        fout<<maximul(1, n, 1, a, b).ssec<<'\n';
    }
    /*
    for(int i=1; i<=4*n; i++)
    {
        cout<<A[i].ssec<<' ';
    }
    */


    fin.close();
    fout.close();
    return 0;
}