Cod sursa(job #2902778)

Utilizator Teodor_AxinteAxinte Teodor-Ionut Teodor_Axinte Data 16 mai 2022 20:07:30
Problema Range minimum query Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <iostream>

using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");

const int oo = 9999999;
const int N = 100010;

int n, m, o, a, b;
int input[N], segTree[4 * N + 10];

void constructTree(int input[], int segTree[], int low, int high, int pos)
{
    if (low == high)
    {
        segTree[pos] = input[low];
        return;
    }
    int mid = (low + high) / 2;
    constructTree(input, segTree, low, mid, 2 * pos + 1);
    constructTree(input, segTree, mid + 1, high, 2 * pos + 2);
    segTree[pos] = min(segTree[2 * pos + 1], segTree[2 * pos + 2]);
}

int rangeMinQuery(int segTree[], int Qlow, int Qhigh, int low, int high, int pos)
{
    if (Qlow <= low && Qhigh >= high) // total overlap
        return segTree[pos];
    if (Qlow > high || Qhigh < low) // no overlap
        return oo;
    int mid = (low + high) / 2;
    return min(rangeMinQuery(segTree, Qlow, Qhigh, low, mid, 2 * pos + 1),
               rangeMinQuery(segTree, Qlow, Qhigh, mid + 1, high, 2 * pos + 2)); // double overlap
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < n; i++)
        fin >> input[i];
    for (int i = 0; i < 4 * n; i++)
        segTree[i] = oo;
    constructTree(input, segTree, 0, n - 1, 0);
    for (; m != 0; m--)
    {
        fin >> a >> b;
        fout << rangeMinQuery(segTree, a - 1, b - 1, 0, n - 1, 0) << '\n';
    }
    return 0;
}