Cod sursa(job #3325224)

Utilizator alex.iovita.23@gmail.comIovita Alexandru [email protected] Data 24 noiembrie 2025 23:33:05
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.55 kb
#include<bits/stdc++.h>
#define int long long
#define DIM 100100

using namespace std;

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

int n , m , a[DIM];

struct Node{
    int sum , pref , suf , best;
};

Node A[4 * DIM];

Node combine(Node L , Node R){
    Node rez;
    rez.sum = L.sum + R.sum;
    rez.pref = max(L.pref , L.sum + R.pref);
    rez.suf = max(R.suf , R.sum + L.suf);
    rez.best = max({L.best , R.best , L.suf + R.pref});
    return rez;
}

inline void build(int nod , int st , int dr){
    if(st == dr){
        A[nod] = {a[st] , a[st] , a[st] , a[st]};
    }
    else{
        int mid = (st + dr) / 2;
        build(2 * nod , st , mid);
        build(2 * nod + 1 , mid + 1 , dr);
        A[nod] = combine(A[2 * nod] , A[2 * nod + 1]);
    }
}

Node query(int nod , int st , int dr , int a , int b){
    if(a <= st && dr <= b)
        return A[nod];

    int mid = (st + dr) / 2;

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

    Node left = query(nod*2, st, mid, a, b);
    Node right = query(nod*2+1, mid+1, dr, a, b);
    return combine(left, right);
}


signed main(){
    ios::sync_with_stdio(false);
    fin.tie(0) , fout.tie(0);
    fin >> n >> m;
    for(int i = 1 ; i <= n ; i++)
        fin >> a[i];
    build(1 , 1 , n);
    for(int i = 1 ; i <= m ; i++){
        int a , b;
        fin >> a >> b;
        Node rez = query(1 , 1 , n ,a , b);
        fout << rez.best <<'\n';
    }
}