Cod sursa(job #3367843)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 11 octombrie 2026 12:35:40
Problema SequenceQuery Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.52 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e5;

struct Node {
    int suma;
    int sufmax;
    int prefmax;
    int smax;
};

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

Node merge(Node a, Node b) {
    Node c;
    c.suma = a.suma + b.suma;
    c.sufmax = max(b.sufmax, a.sufmax + b.suma);
    c.prefmax = max(a.prefmax, a.suma + b.prefmax);
    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] = {v[st], v[st], v[st], 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]);
    }
}

Node query(int node, int st, int dr, int x, int y) {
    if(x <= st && dr <= y) {
        return aint[node];
    } else {
        int mid = (st + dr) / 2;
        Node L = {-1000000, -1000000, -1000000, -1000000}, R = {-1000000, -1000000, -1000000, -1000000};
        if(x <= mid) {
            L = query(2 * node, st, mid, x, y);
        }
        if(mid + 1 <= y) {
            R = query(2 * node + 1, mid + 1, dr, x, y);
        }
        return merge(L, R);
    }
}

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);
    for(int i = 1; i <= q; i++) {
        int x, y;
        cin >> x >> y;
        cout << query(1, 1, n, x, y).smax << '\n';
    }
}