Cod sursa(job #1234397)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 septembrie 2014 12:30:00
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "rmq.in";
const char outfile[] = "rmq.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int MAXLG = 20;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

int N, M, rmq[MAXLG][MAXN], Lg[MAXN];

int Query(int x, int y) {
    int lg = Lg[y - x + 1];
    int ans = rmq[lg][x]; /// [x, y] = [x + 2 ^ (y - x + 1) - 1], [y - 2 ^ (y - x + 1) + 1], y]
    if(ans > rmq[lg][y - (1 << lg) + 1])
        ans = rmq[lg][y - (1 << lg) + 1];
    return ans;
}

int main() {
    fin >> N >> M;
    for(int i = 2 ; i <= N ; ++ i)
        Lg[i] = Lg[i >> 1] + 1;
    for(int i = 1 ; i <= N ; ++ i)
        fin >> rmq[0][i];
    for(int i = 1 ; (1 << i) <= N ; ++ i)
        for(int j = 1 ; j + (1 << i) - 1 <= N ; ++ j) {
            rmq[i][j] = rmq[i - 1][j];
            int aux = 1 << (i - 1);
            /// rmq[i][j] = [j, j + 2 ^ i - 1] = [j, j + 2 ^ (i - 1) -1], [j + 2 ^ (i - 1), j + 2 ^ (i - 1) + 2 ^ (i - 1)  - 1]
            if(rmq[i][j] > rmq[i - 1][j + aux])
                rmq[i][j] = rmq[i - 1][j + aux];
        }
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        fin >> x >> y;
        fout << Query(x, y) << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}