Cod sursa(job #2336742)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 5 februarie 2019 15:32:54
Problema Range minimum query Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("rmq.in");
ofstream g("rmq.out");
int paw2[20], sparse[100005][20], n, m, i, j, val, a, b, logof2[100005], ct, v[100005];
void create_pows(int n)
{
    int val = 2, k = 1;
    paw2[0] = 1;
    while(val <= n)
    {
        paw2[k] = val;
        val = val * 2;
        k++;
    }
}
void create_logs(int n)
{
    logof2[1] = 0;
    int val = 2, k = 1;
    while(val <= n)
    {
        logof2[val] = k;
        k++;
        val = val * 2;
    }
    for(int i = 2; i <= n; i ++)
        if(logof2[i] == 0)logof2[i] = logof2[i - 1];
}
void rmq(int left, int right)
{
    int lenght = right - left + 1;
    int k = logof2[lenght] + 1;
    g << min(v[sparse[left][k]], v[sparse[left + lenght - k][k]]) << "\n";
}
int main()
{
    f >> n >> m;
    create_logs(n);
    create_pows(n);
    ct = logof2[n];
    for(i = 1; i <= n; i ++)
        f >> v[i];
    for(i = 1; i <= n; i ++)
        sparse[i][1] = i;
    for(j = 2; j <= ct + 1; j ++)
    {
        val = paw2[j - 2];
        for(i = 1; i <= n - paw2[j - 1] + 1; i ++)
            if(v[sparse[i][j - 1]] < v[sparse[i + val][j - 1]])sparse[i][j] = sparse[i][j - 1];
            else sparse[i][j] = sparse[i + val][j - 1];
    }
    for(i = 1; i <= m; i ++)
    {
        f >> a >> b;
        rmq(a, b);
    }
    return 0;
}