Cod sursa(job #1988678)

Utilizator Horia14Horia Banciu Horia14 Data 4 iunie 2017 11:02:41
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include<cstdio>
#define MAX_N 100000
#define MAX_LOG 17
using namespace std;

int log(int x)
{
    return 31 - __builtin_clz(x);
}

int sparse[MAX_N][MAX_LOG], v[MAX_N];

int rmq(int low, int high)
{
    int l, k;
    l = high - low + 1;
    k = log(l);
    if(v[sparse[low][k]] <= v[sparse[low + l - (1<<k)][k]])
        return v[sparse[low][k]];
    else return v[sparse[high - (1<<k) + 1][k]];
}

int main()
{
    int n, m, i, j, x, y;
    FILE *fin, *fout;
    fin = fopen("rmq.in","r");
    fout = fopen("rmq.out","w");
    fscanf(fin,"%d%d",&n,&m);
    for(i=0; i<n; i++)
        fscanf(fin,"%d",&v[i]);
    for(i=0; i<n; i++)
        sparse[i][0] = i;
    for(j=1; (1 << j) <= n; j++)
        for(i=0; i + (1 << j) - 1 < n; i++)
            if(v[sparse[i][j-1]] < v[sparse[i + (1 << (j - 1))][j - 1]])
                sparse[i][j] = sparse[i][j-1];
            else sparse[i][j] = sparse[i + (1 << (j - 1))][j-1];

    for(i=1; i<=m; i++)
    {
        fscanf(fin,"%d%d",&x,&y);
        fprintf(fout,"%d\n",rmq(x-1,y-1));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}