Cod sursa(job #638956)

Utilizator andrei-alphaAndrei-Bogdan Antonescu andrei-alpha Data 22 noiembrie 2011 01:26:37
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
using namespace std;

#include <set>
#include <map>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <utility>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>

#define oo (1<<30)
#define f first
#define s second
#define II inline
#define db double
#define ll long long
#define pb push_back
#define mp make_pair
#define Size(V) ((ll)(V.size()))
#define all(V) (V).begin() , (V).end()
#define CC(V) memset((V),0,sizeof((V)))
#define CP(A,B) memcpy((A),(B),sizeof((B)))
#define FOR(i,a,b) for(int (i)=(a);(i)<=(b);++(i))
#define REP(i, N) for (int (i)=0;(i)<(int)(N);++(i))
#define FORit(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); ++it)
#define printll(x) printf("%lld",(x))
#define printsp() printf(" ")
#define newline() printf("\n")
#define readll(x) scanf("%lld",&(x))
#define debugll(x) fprintf(stderr,"%lld\n",(x))

#define IN "rmq.in"
#define OUT "rmq.out"
#define N_MAX (1<<17)

typedef vector<int> VI;
typedef pair<int,int> pi;
typedef pair<short int,short int> ps;
typedef vector<string> VS;
template<class T> string toString(T n) {ostringstream ost;ost<<n;ost.flush();return ost.str();}

int N,M,V[N_MAX];
int Pow2[N_MAX],Rmq[18][N_MAX];

II void scan()
{
    freopen(IN,"r",stdin);
    freopen(OUT,"w",stdout);

    scanf("%d%d",&N,&M);
    FOR(i,1,N)
        scanf("%d",V+i);
}

II int query_rmq(int x,int y)
{
    int step = Pow2[y - x];
    return min(Rmq[step][x], Rmq[step][y - (1<<step) + 1 ]);
}

II void solve()
{
    Pow2[0] = 0;
    Pow2[1] = 0;
    FOR(i,2,N)
        Pow2[i] = Pow2[i / 2] + 1;

    FOR(i,1,N)
        Rmq[0][i] = V[i];

    FOR(step,1,16)
    FOR(i,1,N)
        Rmq[step][i] = min(Rmq[step - 1][i],Rmq[step - 1][ min(N,i + (1<<(step - 1))) ] );

    int x,y;
    FOR(i,1,M)
    {
        scanf("%d%d",&x,&y);
        printf("%d\n", query_rmq(x,y) );
    }
}

int main()
{
    scan();
    solve();
    return 0;
}