Cod sursa(job #2534590)

Utilizator mihailescu_eduardMihailescu Eduard-Florin mihailescu_eduard Data 30 ianuarie 2020 19:11:51
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
//#pragma GCC optimize ("O3")
//#pragma GCC target ("sse4")

#include <bits/stdc++.h>

using namespace std;

#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << endl; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for (auto it = d.b; it != d.e; ++it)
    *this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "


// CHECK THE LIMITS
typedef long long ll;

const int MOD = 1000000007;
const ll INFLL = 1e18;
const int INF = 1e9;
const int NMAX = 1000005;

const int K = 18;

int gcd(int a, int b) {
  return b ? gcd(b, a%b) : a;
} 

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

// sparse table sp[i][j] holds the minumum for range [i, i + 2^j - 1] 18-> 2^18 
int sp[NMAX][K];
int Log[NMAX];
int v[NMAX];
int n,m;

void calculate_log()
{
    Log[1] = 0;
    for(int i = 2; i< NMAX; ++i)
    {
        Log[i] = Log[i>>1]+1;
    }
}

void calculate_sp()
{
    for(int i = 0; i < n; ++i)
    {
        sp[i][0] = v[i];
    }
    for(int j = 1; j<= K; ++j)
    {
        for(int i = 0; i + (1 << j) <= n; i++)
        {
            // minimum of the two halves of the interval using dp approach
            sp[i][j] = min(sp[i][j-1], sp[i+ (1 << (j-1))][j-1]);
        }
    }
}


int calculate_min(int left, int right)
{
    int j = Log[right-left+1]; // number of elements
    return min(sp[left][j], sp[right- (1<<j) + 1][j]);
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    fin >> n>> m;
    for(int i = 0; i< n; ++i)
    {
        fin >> v[i];
    }
    // Precalculate sp and log2 array
    calculate_log();
    calculate_sp();

    for(int i = 0; i< m; ++i)
    {
        int left,right;
        fin >> left >> right;

        left--;
        right--;
        fout << calculate_min(left,right) << '\n';
    }


    return 0;
}