Cod sursa(job #3376313)

Utilizator AndreiRaresAcatrini Rares Andrei AndreiRares Data 17 noiembrie 2026 12:04:12
Problema SequenceQuery Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.35 kb
#include <iostream>
#include <fstream>
using namespace std;

#ifdef LOCAL
#define fin cin
#define fout cout
#else
ifstream fin("sequencequery.in");
ofstream fout("sequencequery.out");
#endif

int a[100001];

struct Nod {
	int s, smax, smax_pref, smax_suf;
} aint[400000];

Nod combina(Nod a, Nod b) {
	Nod rez;
	rez.s = a.s + b.s;
	rez.smax = max(max(a.smax, b.smax), a.smax_suf + b.smax_pref);
	rez.smax_pref = max(a.smax_pref, a.s + b.smax_pref);
	rez.smax_suf = max(b.smax_suf, b.s + a.smax_suf);
	return rez;
}

void build(int nod, int st, int dr) {
	if (st == dr) {
		aint[nod].s = a[st];
		aint[nod].smax = a[st];
		aint[nod].smax_pref = a[st];
		aint[nod].smax_suf = a[st];
		return;
	}
	int mid = (st + dr) / 2;
	build(nod * 2, st, mid);
	build(nod * 2 + 1, mid + 1, dr);
	aint[nod] = combina(aint[nod * 2], aint[nod * 2 + 1]);
}

Nod query(int nod, int st, int dr, int x, int y) {
	if (x <= st && dr <= y)
		return aint[nod];
	int mid = (st + dr) / 2;
	if (x <= mid && mid < y)
		return combina(query(nod * 2, st, mid, x, y), query(nod * 2 + 1, mid + 1, dr, x, y));
	else if (x <= mid)
		return query(nod * 2, st, mid, x, y);
	else
		return query(nod * 2 + 1, mid + 1, dr, x, y);
}

int main() {
	int n, m, x, y;
	fin >> n >> m;
	for (int i=1; i<=n; i++)
		fin >> a[i];
	build(1, 1, n);
	while (m--) {
		fin >> x >> y;
		fout << query(1, 1, n, x, y).smax << '\n';
	}
}