Cod sursa(job #1974992)

Utilizator Horia14Horia Banciu Horia14 Data 29 aprilie 2017 17:35:04
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<cstdio>
#define MAX_N 100000
#define MAX_LOG 17
using namespace std;

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

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

int RMQ(int low, int high)
{
    int l = high - low + 1;
    int 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 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=0; i<m; i++)
    {
        fscanf(fin,"%d%d",&x,&y);
        fprintf(fout,"%d\n",RMQ(x-1,y-1));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}