Cod sursa(job #3124629)

Utilizator Roxana_3Asavei Roxana Roxana_3 Data 29 aprilie 2023 15:46:21
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#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;
}