Pagini recente » Cod sursa (job #1366739) | Cod sursa (job #1839570) | Cod sursa (job #2594042) | Cod sursa (job #2820332) | Cod sursa (job #1784759)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#define INF (1LL<<30)
using namespace std;
ifstream f("rmq.in");
ofstream g("rmq.out");
int n, m, k, len, dx[1005], dy[1005], mn[1005], v[100005], buc[100005];
void Seq()
{
int i, temp, beg, end;
beg = 1;
while (beg <= n)
{
end = beg + len - 1;
if (end > n) end = n;
k++; dx[k] = beg; dy[k] = end;
temp = INF;
for (i = beg; i <= end; i++)
{
temp = min(temp, v[i]);
buc[i] = k;
}
mn[k] = temp;
beg += len;
}
}
int Search(int i1, int i2)
{
int i, ans = INF , actx=buc[i1], acty=buc[i2];
if (actx != acty)
{
for (i = i1; i <= dy[actx]; i++)
ans = min(ans, v[i]);
for (i = dx[acty]; i <= i2; i++)
ans = min(ans, v[i]);
}
else
for (i = i1; i <= i2; i++)
ans = min(ans, v[i]);
for (i = actx + 1; i < acty; i++)
ans = min(ans, mn[i]);
return ans;
}
int main()
{
int i, x, y;
f >> n >> m;
len = (int)sqrt(n);
for (i = 1; i <= n; i++)
f >> v[i];
Seq();
for (i = 1; i <= m; i++)
{
f >> x >> y;
g << Search(x, y)<<"\n";
}
return 0;
}