Cod sursa(job #3357239)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 7 iunie 2026 14:12:05
Problema SequenceQuery Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e5;
struct Node {
    int suma;
    int smax;
    int prefmax;
    int sufmax;
};

int v[NMAX + 1];
Node aint[4 * NMAX];
Node sol;

Node merge(Node a, Node b) {
    Node c;
    c.suma = a.suma + b.suma;
    c.prefmax = max(a.prefmax, a.suma + b.prefmax);
    c.sufmax = max(b.sufmax, a.sufmax + b.suma);
    c.smax = max(max(a.smax, b.smax), a.sufmax + b.prefmax);
    return c;
}

void build(int node, int st, int dr) {
    if(st == dr) {
        aint[node].suma = v[st];
        aint[node].smax = v[st];
        aint[node].prefmax = v[st];
        aint[node].sufmax = v[st]; 
    } else {
        int mid = (st + dr) / 2;
        build(2 * node, st, mid);
        build(2 * node + 1, mid + 1, dr);
        aint[node] = merge(aint[2 * node], aint[2 * node + 1]);
    }
}

void query(int node, int st, int dr, int x, int y) {
    if(x <= st && dr <= y) {
        sol = merge(sol, aint[node]);
    } else {
        int mid = (st + dr) / 2;
        if(x <= mid) {
            query(2 * node, st, mid, x, y);
        }
        if(mid + 1 <= y) {
            query(2 * node + 1, mid + 1, dr, x, y);
        }
    }
}


int main() {
    ifstream cin("sequencequery.in");
    ofstream cout("sequencequery.out");
    int n, q;
    cin >> n >> q;
    for(int i = 1; i <= n; i++) {
        cin >> v[i];
    }
    build(1, 1, n);
    while(q--) {
        int x, y;
        cin >> x >> y;
        sol = {0, (int)-1e9, (int)-1e9, (int)-1e9};
        query(1, 1, n, x, y);
        cout << sol.smax << '\n';
    }
}