Cod sursa(job #2465890)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 30 septembrie 2019 23:29:59
Problema SequenceQuery Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.01 kb
#include <bits/stdc++.h>
#define N 100005

using namespace std;

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

struct arbore
{
    long long subMax;
    long long sumAll;
    long long sufMax;
    long long prefMax;
};

int n, m;
long long ans = LLONG_MIN, sumMax = LLONG_MIN;
bool beg = 1;
arbore aint[4 * N];

void getBest(arbore &T, arbore fiuSt, arbore fiuDr)
{
    T.sumAll = fiuSt.sumAll + fiuDr.sumAll;

    T.subMax = max(fiuSt.subMax, fiuDr.subMax);
    T.subMax = max(T.subMax, fiuSt.prefMax + fiuDr.sufMax);

    T.sufMax = max(fiuSt.sufMax, fiuSt.sumAll + fiuDr.sufMax);
    T.prefMax = max(fiuDr.prefMax, fiuDr.sumAll + fiuSt.prefMax);
}

void buildTree(int nod, int st, int dr)
{
    if (st == dr)
    {
        int x;
        fin >> x;
        aint[nod].subMax = aint[nod].sumAll = aint[nod].sufMax = aint[nod].prefMax = x;
    }
    else
    {
        int mij = (st + dr) / 2;
        buildTree(2 * nod, st, mij);
        buildTree(2 * nod + 1, mij + 1, dr);

        getBest(aint[nod], aint[2 * nod], aint[2 * nod + 1]);
    }
}

void Query(int nod, int st, int dr, int x, int y)
{
    if (st >= x && dr <= y)
    {
        ans = max(ans, aint[nod].subMax);
        if (beg)
        {
            sumMax = aint[nod].prefMax;
            beg = 0;
        }
        else
        {
            ans = max(ans, sumMax + aint[nod].sufMax);
            sumMax = max(sumMax + aint[nod].sumAll, aint[nod].prefMax);
            ans = max(ans, sumMax);
        }
    }
    else
    {
        int mij = (st + dr) / 2;
        if (x <= mij)
            Query(2 * nod, st, mij, x, y);
        if (y > mij)
            Query(2 * nod + 1, mij + 1, dr, x, y);
    }
}

int main()
{
    fin >> n >> m;
    buildTree(1, 1, n);

    for (int i = 1; i <= 3; i++)
    {
        int x, y;
        fin >> x >> y;

        beg = 1;
        ans = sumMax = LLONG_MIN;

        Query(1, 1, n, x, y);
        fout << ans << "\n";
    }
    return 0;
}