Pagini recente » Cod sursa (job #1871470) | Cod sursa (job #1724713) | Cod sursa (job #1662317) | Cod sursa (job #2824418) | Cod sursa (job #3225736)
//#include <iostream>
#include <fstream>
using namespace std;
int a[250001];
int rmq[250001][18], LOG[250001];
//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;
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;
if (y == 0) cout << x << '\n';
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