Cod sursa(job #1839440)

Utilizator jurjstyleJurj Andrei jurjstyle Data 2 ianuarie 2017 21:44:21
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>
#include <cmath>
#include <vector>

using namespace std;

FILE* fin=fopen("rmq.in","r");
ofstream g("rmq.out");


int n, m;
vector <int> V;
vector <int> Segm_Tree;

const unsigned maxb=1024;
char buf[maxb];
unsigned ptr=maxb;

inline unsigned getInt(){
    unsigned nr=0;
    while(buf[ptr]<'0'||'9'<buf[ptr])         if(++ptr>=maxb)
            fread(buf,maxb,1,fin),ptr=0;
    while('0'<=buf[ptr]&&buf[ptr]<='9'){         nr=nr*10+buf[ptr]-'0';         if(++ptr>=maxb)
            fread(buf,maxb,1,fin),ptr=0;
    }
    return nr;
}





void initialize(int arb_curent, int st, int dr)
{
    if (st == dr)
        Segm_Tree[arb_curent] = st;
    else
    {
        int m = (st + dr) / 2;
        initialize ( 2 * arb_curent, st, m);
        initialize ( 2 * arb_curent + 1, m + 1, dr);
        if ( V[Segm_Tree[2 * arb_curent]] <= V[Segm_Tree[2 * arb_curent + 1]] )
            Segm_Tree[arb_curent] = Segm_Tree[2 * arb_curent];
        else
            Segm_Tree[arb_curent] = Segm_Tree[2 * arb_curent + 1];
    }
}
int query (int arb_curent, int st, int dr, int i, int j)
{
    if ( i == st && j == dr )
        return Segm_Tree[arb_curent] ;
    int m = ( st + dr ) / 2 ;
    if ( j <= m )
        return query ( 2 * arb_curent, st, m, i, j ) ;
    if ( m < i )
        return query ( 2 * arb_curent + 1, m + 1, dr, i, j ) ;
    int p1 = query ( 2 * arb_curent, st, m, i, m );
    int p2 = query( 2 * arb_curent + 1, m + 1, dr, m + 1, j );
    if ( V[p1] <= V[p2] )
        return p1;
    else
        return p2;
}
int main()
{
    n = getInt();
    m = getInt();
    V.resize (n + 1);
    for (int i = 1; i <= n; ++i)
        V[i] = getInt();
    Segm_Tree.resize( 2 * ( pow (2, log2(n) + 1) ) );
    initialize(1, 1, n);
    for (int i = 1; i <= m; ++i)
    {
        int x, y;
        x = getInt();
        y = getInt();
        g << V[query(1, 1, n, x, y)] << "\n";
    }
}