Cod sursa(job #2724600)

Utilizator NeganAlex Mihalcea Negan Data 17 martie 2021 13:58:48
Problema SequenceQuery Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <bits/stdc++.h>

using namespace std;

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

const int oo = 2000000000;
const int NMAX = 200005;
long long ans, S;
int n, m;
long long A[4 * NMAX], B[4 * NMAX], C[4 * NMAX], SUM[4 * NMAX];
int a[NMAX];

int Leftson(int x)
{
    return 2 * x;
}

int Rightson(int x)
{
    return 2 * x + 1;
}

void Build(int node, int left, int right)
{
    if(left == right)
    {
        A[node] =  a[left];
        B[node] =  a[left];
        C[node] =  a[left];
        SUM[node] = a[left];
        return;
    }
    int mid = (left + right) / 2;
    Build(Leftson(node), left, mid);
    Build(Rightson(node), mid + 1, right);
    A[node] = max(A[Leftson(node)], SUM[Leftson(node)] + A[Rightson(node)]);
    B[node] = max(B[Rightson(node)], SUM[Rightson(node)] + B[Leftson(node)]);
    C[node] = max(max(C[Leftson(node)], C[Rightson(node)]), B[Leftson(node)] + A[Rightson(node)]);
    SUM[node] = SUM[Leftson(node)] + SUM[Rightson(node)];
}

void Update(int node, int left, int right, int pos, int val)
{
    if(left == right)
    {
        A[node] = max(0, val);
        B[node] = max(0, val);
        C[node] = max(0, val);
        SUM[node] = val;
        return;
    }
    int mid = (left + right) / 2;
    if(pos <= mid)
        Update(Leftson(node), left, mid, pos, val);
    else
        Update(Rightson(node), mid + 1, right, pos, val);
    A[node] = max(A[Leftson(node)], SUM[Leftson(node)] + A[Rightson(node)]);
    B[node] = max(B[Rightson(node)], SUM[Rightson(node)] + B[Leftson(node)]);
    C[node] = max(max(C[Leftson(node)], C[Rightson(node)]), B[Leftson(node)] + A[Rightson(node)]);
    SUM[node] = SUM[Leftson(node)] + SUM[Rightson(node)];
}

void Query(int node, int left, int right, int lquery, int rquery)
{
    if(lquery <= left && right <= rquery)
    {
        /*if(S < 0)
            S = 0;*/
        ans = max(ans, max(S + A[node], C[node]));
        S = max(S + SUM[node], B[node]);
        return;
    }
    int mid = (left + right) / 2;
    if(lquery <= mid)
        Query(Leftson(node), left, mid, lquery, rquery);
    if(rquery > mid)
        Query(Rightson(node), mid + 1, right, lquery, rquery);
}
void Citire()
{
    int i;
    fin >> n >> m;
    for(i = 1;i <= n;i++)
        fin >> a[i];
    Build(1, 1, n);
    for(i = 1;i <= m;i++)
    {
        int op, a, b;
        fin >> a >> b;
        ans = S = -oo;
        Query(1, 1, n, a, b);
        fout << ans << "\n";
    }
}

int main()
{
    Citire();
    return 0;
}