Cod sursa(job #3225731)

Utilizator ArcherraikoNedelcu Stefan Daniel Archerraiko Data 18 aprilie 2024 17:14:38
Problema Stramosi Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.51 kb
//#include <iostream>
#include <fstream>
using namespace std;
int a[100001];
int rmq[100001][18], LOG[100001];
//query in O(1), functioneaza doar pentru functii idempotente
int query1(int x, int y) {
    int k = LOG[y - x + 1];
    return min(rmq[x][k], rmq[y - (1 << k) + 1][k]);
}
//query in O(log(n)), merge si pe functii neidempotente
int query2(int x, int y) {
    int diff = y;
    int st = x;
    int sol = 0;
    for (int i = 0; (1 << i) <= diff; i++) {
        if ((1 << i) & diff) {
            st = rmq[st][i];
        }
    }
    return st;
}
int main() {
    ifstream cin("stramosi.in");
    ofstream cout("stramosi.out");
    int n,m,x,y,j=1;
    cin >> n>>m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 2; i <= n; i++) {
        LOG[i] = LOG[i / 2] + 1;
    }
    for (int i = 1; i <= n; i++) {
        rmq[i][0] = a[i];
    }
    for (int j = 1; (1 << j) <= n; j++) {
        for (int i = 1; i + (1 << j) - 1 <= n; i++) {
            rmq[i][j] = rmq[rmq[i][(1 << (j - 1))-1]][(1 << (j - 1))-1];
        }
    }
    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        cout<<query2(x,y)<<'\n';
    }
    return 0;
}

// https://infoarena.ro/problema/rmq
// https://www.pbinfo.ro/probleme/1735/divquery
// https://www.pbinfo.ro/probleme/3860/consecutive1
// https://www.infoarena.ro/problema/stramosi
// https://www.infoarena.ro/problema/lca
// https://www.youtube.com/watch?v=0jWeUdxrGm4
// https://www.youtube.com/watch?v=oib-XsjFa-M