Cod sursa(job #3235358)

Utilizator Zen4415Stefan Zen4415 Data 17 iunie 2024 13:25:33
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");

const int NMAX = 1e5;
int a[NMAX + 1];
int rmq[NMAX + 1][20], LOG[NMAX + 1];


//query in O(log(n)), merge si pe functii neidempotente
int query(int q, int p) {
    int current = q;
    for (int j = 0; (1 << j) <= p; j++) {
        if (p & (1 << j)) {
            current = rmq[current][j];
            if (current == 0) break; // daca ajungem la 0, inseamna ca nu mai avem stramosi
        }
    }
    return current;
}

int main() {
    int n, m;

    // citire
    fin >> n >> m;
    for(int i = 1; i <= n; i++) {
        fin >> a[i];
    }

    // precompute
    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 <= n; i++) {
            if (rmq[i][j - 1] != 0) {
                rmq[i][j] = rmq[ rmq[i][j - 1] ][j - 1];
            } else {
                rmq[i][j] = 0;
            }
        }
    }

    // queries
    for(int i = 1; i <= m; i++) {
        int q, p;
        fin >> q >> p;
        fout << query(q, p) << endl;
    }
    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 */