Pagini recente » Cod sursa (job #469823) | Cod sursa (job #1548847) | Cod sursa (job #2970248) | Cod sursa (job #621234) | Cod sursa (job #3235359)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");
const int NMAX = 250001;
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 */