Cod sursa(job #3142484)

Utilizator Raul_AArdelean Raul Raul_A Data 21 iulie 2023 20:39:22
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.1 kb
#include <bits/stdc++.h>
#define cin in
#define cout out
#define ll long long
using namespace std;

const string file_name("sequencequery");

ifstream in(file_name + ".in");
ofstream out(file_name + ".out");

struct tree_node{
    ll sum, pref_scmax, suff_scmax, scmax;
};

int n, k, x, y;
vector<int> v;
vector<tree_node> tree;

tree_node update(tree_node left_node, tree_node right_node)
{
    tree_node current_node;

    current_node.sum =
        left_node.sum + right_node.sum;

    current_node.pref_scmax =
        std::max(left_node.pref_scmax,
                 left_node.sum + right_node.pref_scmax);

    current_node.suff_scmax =
        std::max(right_node.suff_scmax,
                 right_node.sum + left_node.suff_scmax);

    current_node.scmax =
        std::max(left_node.suff_scmax + right_node.pref_scmax,
                 std::max(left_node.scmax, right_node.scmax));

    return current_node;
}

void build(int nod, int st, int dr)
{
    if (st == dr)
        tree[nod].sum = tree[nod].pref_scmax = tree[nod].suff_scmax = tree[nod].scmax = v[st];
    else
    {
        int m = (st + dr) / 2;

        build(2 * nod, st, m);
        build(2 * nod + 1, m + 1, dr);

        tree[nod] = update(tree[2 * nod], tree[2 * nod + 1]);
    }
}

tree_node query(int nod, int st, int dr, int a, int b)
{
    if (a <= st and dr <= b)
        return tree[nod];
    else
    {
        int m = (st + dr) / 2;

        if (b <= m)
            return query(2 * nod, st, m, a, b);
        if (m + 1 <= a)
            return query(2 * nod + 1, m + 1, dr, a, b);

        tree_node left_node = query(2 * nod, st, m, a, b),
                  right_node = query(2 * nod + 1, m + 1, dr, a, b);
        return update(left_node, right_node);
    }
}

void read()
{
    cin >> n >> k;

    v.resize(n + 5);
    tree.resize(4 * n + 5);

    for (int i = 1; i <= n; i++)
        cin >> v[i];

    build(1, 1, n);

    while (k--)
    {
        cin >> x >> y;
        cout << query(1, 1, n, x, y).scmax << '\n';
    }
}

int main()
{
    read();
    return 0;
}