Cod sursa(job #388691)

Utilizator alexandru92alexandru alexandru92 Data 30 ianuarie 2010 18:47:30
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
//      rmq.cpp
//      
//      Copyright 2010 SpeeDemon <virtualdemon@ubuntu>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.

#include <fstream>
#include <algorithm>
#define inf 0x3f3f3f3f

/*
 * 
 */
using namespace std;
int *v;
inline int min( int x, int y )
{
	return y^( (x^y) & -(x<y) );
}
inline void Update( int vertex, int left, int right, int p, int x )
{
	if( left == right )
	{
		v[vertex]=x;
		return;
	}
	int middle=left+(right-left)/2;
	if( p <= middle )
	   Update( (vertex<<1), left, middle, p, x );
    else Update( (vertex<<1)|1, middle+1, right, p, x );
    v[vertex]=min( v[(vertex<<1)], v[(vertex<<1)|1] );
} 
inline int Query( int vertex, int left, int right, int a, int b )
{
	if( a <= left && right <= b )
	  return v[vertex];
	int min=inf, middle=left+(right-left)/2;
	if( a <= middle )
	   min=Query( vertex<<1, left, middle, a, b );
	if( b > middle )
	   min=::min( min, Query( (vertex<<1)|1, middle+1, right, a, b ) );
	return min;
}
int main()
{
	int n, m, i, x, y; 
	ifstream in("rmq.in");
	in>>n>>m;
	v=new int[2*n+1];
	fill( v, v+2*n+1, inf );
	for( i=1; i <= n; ++i )
	{
		in>>x;
		Update( 1, 1, n, i, x );
	}
	ofstream out("rmq.out");
	for( i=1; i <= m; ++i )
	{
		in>>x>>y;
		out<<(Query( 1, 1, n, x, y ) )<<'\n';
	}
	return 0;
}