Cod sursa(job #2693144)

Utilizator raducostacheRadu Costache raducostache Data 4 ianuarie 2021 21:44:36
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
//
//  main.cpp
//  RMQ
//
//  Created by Radu Costache on 04/01/2021.
//  Copyright © 2021 Radu Costache. All rights reserved.
//

#include <stdio.h>
#include <math.h>

#define NMAX 100005
#define MIN(x,y) (((x)<(y))?(x):(y))

int n, q, v[NMAX], sparse[NMAX][25];

int main(int argc, const char * argv[]) {
    // insert code here...
    FILE *f = fopen("rmq.in", "r");
    FILE *g = fopen("rmq.out", "w");
    fscanf(f, "%d %d\n", &n, &q);
    for (int i = 1; i <= n; ++i) {
        fscanf(f, "%d\n", v+i);
        sparse[i][0] = v[i];
    }
    for (int j = 1; (1 << j) <= n; ++j)
        for (int i = 1; i + (1 << j) - 1 <= n; ++i) {
            sparse[i][j] = MIN(sparse[i][j - 1], sparse[i + (1 << (j - 1))][j - 1]);
        }
    while (q--) {
        int x, y;
        fscanf(f, "%d %d\n", &x, &y);
        int tmp = log2(y - x + 1);
        fprintf(g, "%d\n", MIN(sparse[x][tmp], sparse[y-(1<<tmp)+1][tmp]));
        
    }
    return 0;
}