Cod sursa(job #543076)

Utilizator dacyanMujdar Dacian dacyan Data 27 februarie 2011 15:26:34
Problema SequenceQuery Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.29 kb
#include <fstream>
#define DIM 100100
#define INF -100100
using namespace std;

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

long a[4*DIM], b[4*DIM], c[4*DIM], d[4*DIM];
long m, n;
long x, y, poz, val;
long sol, ultim;

void Update(int,int,int);
void Query(int,int,int);

int main()
{
	fin >> n >> m;
	for (poz = 1; poz <= n; ++poz)
	{
		fin >> val;
		Update(1,1,n);
	}
	for (int i = 1; i <= m; ++i)
	{
		fin >> x >> y;
		sol = ultim = INF;
		Query(1,1,n);
		fout << sol << '\n';
	}
	fin.close();
	fout.close();
	return 0;
}

void Update(int nod, int st, int dr)
{
	if (st == dr)
	{
		a[nod] = b[nod] = c[nod] = d[nod] = val;
		return;
	}
	
	int mij = (st + dr) / 2;
	if (poz <= mij) Update(2*nod, st, mij);
	else 			Update(2*nod+1, mij + 1, dr);
	
	d[nod] = d[2*nod] + d[2*nod+1];
	a[nod] = max(a[2*nod], d[2*nod] + a[2*nod+1]);
	b[nod] = max(b[2*nod+1], d[2*nod+1] + b[2*nod]);
	c[nod] = max(max(c[2*nod], c[2*nod+1]), a[2*nod+1] + b[2*nod]);
}

void Query(int nod, int st, int dr)
{
	if (st >= x && dr <= y)
	{
		sol = max(sol, max(c[nod], ultim + a[nod]));
		ultim = max(ultim + d[nod], b[nod]);
		return;
	}
	int mij = (st + dr) / 2;
	if (x <= mij) Query(2*nod, st, mij);
	if (y > mij) Query(2*nod+1, mij+1, dr);
}