Cod sursa(job #3357675)

Utilizator rapidu36Victor Manz rapidu36 Data 12 iunie 2026 19:29:45
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.7 kb
#include <fstream>
#include <vector>
#include <climits>

using namespace std;

struct nod {
    long long prefix, sufix, ssm, stot;
};

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

vector <nod> aint;

int putere_2(int n) {
    int e = 0;
    while ((1 << e) < n) {
        e++;
    }
    return (1 << (e + 1));
}

nod combina(nod &a, nod &b) {
    nod rez = (nod){a.prefix, b.sufix,max(a.ssm, b.ssm), a.stot + b.stot};
    rez.ssm = max(rez.ssm, a.sufix + b.prefix);
    rez.prefix = max(rez.prefix, a.stot + b.prefix);
    rez.sufix = max(rez.sufix, a.sufix + b.stot);
    return rez;
}

void constructie(int p, int st, int dr) {
    if (st == dr) {
        in >> aint[p].stot;
        aint[p].prefix = aint[p].sufix = aint[p].ssm = aint[p].stot;
        return;
    }
    int m = (st + dr) / 2, fs = 2 * p, fd = 2 * p + 1;
    constructie(fs, st, m);
    constructie(fd, m + 1, dr);
    aint[p] = combina(aint[fs], aint[fd]);
}

nod interogare(int p, int st, int dr, int a, int b) {
    if (a <= st && dr <= b) {
        return aint[p];
    }
    int m = (st + dr) / 2, fs = 2 * p, fd = 2 * p + 1;
    if (a <= m) {
        nod rez_st = interogare(fs, st, m, a, b);
        if (m + 1 <= b ) {
            nod rez_dr = interogare(fd, m + 1, dr, a, b);
            return combina(rez_st, rez_dr);
        } else {
            return rez_st;
        }
    }
    nod rez_dr = interogare(fd, m + 1, dr, a, b);
    return rez_dr;
}

int main() {
    int n, q;
    in >> n >> q;
    aint.resize(putere_2(n));
    constructie(1, 1, n);
    for (int i = 0; i < q; i++) {
        int a, b;
        in >> a >> b;
        out << interogare(1, 1, n, a, b).ssm << "\n";
    }
    in.close();
    out.close();
    return 0;
}