Cod sursa(job #156586)

Utilizator pikuAnca Miihai piku Data 12 martie 2008 17:16:52
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include<cstdio>
#define nmax 100010
#define logmax 17

int n, m, v[nmax], lg2[nmax]; 
int a[nmax][logmax];

int main()
{
 freopen("rmq.in", "r", stdin);
 freopen("rmq.out", "w", stdout);
 scanf("%d %d", &n, &m);
 int i, j;
 for(i=0; i<n; i++)
  {
   scanf("%d", &v[i]);
   a[i][0] = i;
  }
 for(i=2; i<=n; i++)
		lg2[i] = lg2[i/2]+1;

 for(j = 1; (1<<j) <= n; j++)
  for(i = 0; i + (1<<j) <=n; i++)
   if(v[ a[i][j-1] ] < v[ a[i + (1<<(j-1))][j-1] ])
			a[i][j] = a[i][j-1];
	else
			a[i][j] = a[i+ (1<<(j-1))][j-1];

 /*
 for(i=0; i<n; i++)
  {
	for(j=1; (1<<j) <= n; j++)
		printf("%d ", a[i][j]);
	printf("\n");
	}
 */

	int x, y;
	while(m>0)
	{
		scanf("%d %d", &x, &y);
		if(v[ a[x][ lg2[y-x+1]] ] < v[ a[y -(1<<lg2[y-x+1])][lg2[y-x+1] ] ])
			printf("%d\n", v[ a[x][ lg2[y-x+1] ]]);
		else
			printf("%d\n", v[ a[y -(1<<lg2[y-x+1])][lg2[y-x+1] ] ]);
		m--;
	}
	return 0;
}