Pagini recente » Cod sursa (job #3221846) | Cod sursa (job #1609476) | Cod sursa (job #87545) | Cod sursa (job #1544119) | Cod sursa (job #3124629)
#include <bits/stdc++.h>
#define N 100000
using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
/**
sparse_table[i][j] = indicele elem minim al secventei [i, i + 2^j - 1]
*/
int sparse_table[N + 3][19];
int n, m, a[N + 5];
void Citire()
{
fin >> n >> m;
for(int i = 1; i <= n; ++i)
fin >> a[i];
}
void Precalculare()
{
/// completam coloana 0
for(int i = 1; i <= n; ++i)
sparse_table[i][0] = i;
int j = 1, exp2j;
for(exp2j = 2; exp2j <= n; exp2j *= 2)
{
for(int i = 1; i + exp2j - 1 <= n; ++i)
{
int ant = exp2j / 2;
int min1 = a[sparse_table[i][j - 1]];
int min2 = a[sparse_table[i + ant][j - 1]];
if(min1 < min2)
sparse_table[i][j] = sparse_table[i][j - 1];
else
sparse_table[i][j] = sparse_table[i + ant][j - 1];
}
j++;
}
}
void Afisare()
{
int c = int(log2(n)) + 1;
for(int i = 1; i <= n; ++i)
{
for(int j = 0; j < c; ++j)
fout << sparse_table[i][j] << " ";
fout << "\n";
}
}
void Rezolvare()
{
int x, y;
for(int i = 1; i <= m; ++i)
{
fin >> x >> y;
if(x > y) swap(x, y);
int ct = y - x + 1;
int col1 = int(log2(ct));
int min1 = a[sparse_table[x][col1]];
int calculate = exp2(col1);
int ramase = ct - calculate;
if(ramase != 0)
min1 = min(min1, a[sparse_table[x + ramase][col1]]);
fout << min1 << "\n";
}
}
int main()
{
Citire();
Precalculare();
// Afisare();
Rezolvare();
return 0;
}