Cod sursa(job #3377546)

Utilizator andrei_sevescusevescu andrei andrei_sevescu Data 23 noiembrie 2026 15:40:50
Problema SequenceQuery Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

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

int INF=1000000;
#define N 100000

struct node {
    long long pref, suf, ssm, st;
};
node aint[N*2];

node comb(node n1, node n2) {
    node n;
    n.st = n1.st + n2.st;
    n.pref = max(n1.pref, n1.st + n2.pref);
    n.suf = max(n2.suf, n1.suf + n2.st);
    n.ssm = max(n1.ssm, n2.ssm);
    n.ssm = max(n.ssm, n1.suf + n2.pref);
    return n;
}

void constructie(int p, int st, int dr) {
    if (st == dr) {
        int x;
        fin >> x;
        aint[p] = node(x, x, x, x);
        return;
    }
    int m = (st + dr) / 2, fs = 2 * p, fd = 2 * p + 1;
    constructie(fs, st, m);
    constructie(fd, m + 1, dr);
    aint[p] = comb(aint[fs], aint[fd]);
}

node interogare(int p, int st, int dr, int a, int b) {
    if(a<=st && dr<=b) {
        return aint[p];
    }
    int mij=(st+dr)/2,fs=2*p,fd=2*p+1;
    node n_st = node(-INF, -INF, -INF, -INF);
    node n_dr = node(-INF, -INF, -INF, -INF);
    if(a<=mij) {
        n_st = interogare(fs, st, mij, a, b);
    }
    if(mij+1<=b) {
        n_dr=interogare(fd, mij + 1, dr, a, b);
    }
    return comb(n_st, n_dr);
}

int main() {
    int n,m;
    fin >> n >> m;
    //fout << m;

    constructie(1, 1, n);
    for (int i = 0; i < m; i++) {
        int a, b;
        fin >> a >> b;
        fout << interogare(1, 1, n, a, b).ssm << "\n";
    }
    return 0;
}