Cod sursa(job #3164509)

Utilizator gianiferSpita Alexandru-Mihai gianifer Data 3 noiembrie 2023 14:59:18
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("sequencequery.in");

ofstream fout("sequencequery.out");

int xl;

struct str
{
    long long ssm = 0, smaxst = 0, smaxdr = 0, suma = 0;
} aint[400050];

str calc(str a, str b)
{
    str c;
    c.ssm = max(max(a.ssm, b.ssm), a.smaxdr + b.smaxst);
    c.smaxdr = max(b.smaxdr, a.smaxdr + b.suma);
    c.smaxst = max(a.smaxst, b.smaxst + a.suma);
    c.suma = a.suma + b.suma;
    return c;
}

void build(int nod, int st, int dr)
{
    if (st == dr)
    {
        fin >> xl;
        aint[nod].smaxdr = xl;
        aint[nod].smaxst = xl;
        aint[nod].ssm = xl;
        aint[nod].suma = xl;
    }
    else
    {
        int mij = (st + dr) / 2;
        build(2 * nod, st, mij);
        build(2 * nod + 1, mij + 1, dr);
        aint[nod] = calc(aint[2 * nod], aint[2 * nod + 1]);
    }
}
str query(int nod, int st, int dr, int x, int y)
{
    if (st >= x && dr <= y)
    {
        return aint[nod];
    }
    else
    {
        int mij = (st + dr) / 2;
        str a, b;
        if (x <= mij)
        {
            a = query(2 * nod, st, mij, x, y);
        }
        if (y >= mij + 1)
        {
            b = query(2 * nod + 1, mij + 1, dr, x, y);
        }
        if (x <= mij && (mij + 1) <= y)
        {
            return calc(a, b);
        }
        else
        {
            if (x <= mij)
            {
                return a;
            }
            else
            {
                return b;
            }
        }
    }
}
int main()
{
    int n, m;
    fin >> n >> m;
    build(1, 1, n);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        fout << query(1, 1, n, x, y).ssm << '\n';
    }
}