Cod sursa(job #3245955)

Utilizator PHOSSESSEDProsie Radu-Teodor PHOSSESSED Data 1 octombrie 2024 11:37:02
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include<fstream>
#include<vector>
#include<stack>
using namespace std;

///shoutout arpa

constexpr int nmax = 1e6 + 11;

int v[nmax / 10], ans[nmax], t[nmax / 10], l[nmax];
vector<int> id[nmax / 10];

int root(int x){return t[x] ? t[x] = root(t[x]) : x;}

int main()
{   
    ifstream cin("rmq.in");
    ofstream cout("rmq.out");

    int n, q, st, dr; cin >> n >> q;
    for(int i = 1; i <= n ; i++)
        cin >> v[i];
    for(int i = 0; i < q ; i++)
    {
        cin >> st >> dr;
        id[dr].push_back(i); l[i] = st;
    }

    stack<int> stiva; ///st contine toti orfanii
    for(int i = 1; i <= n ; i++)
    {
        while(!stiva.empty() && v[stiva.top()] >= v[i])
            t[stiva.top()] = i, stiva.pop();

        stiva.push(i);
        for(auto &it : id[i])
            ans[it] = v[root(l[it])];
    }

    for(int i = 0; i < q ; i++)
        cout << ans[i] << '\n';

}