Cod sursa(job #3338594)

Utilizator pkseVlad Bondoc pkse Data 4 februarie 2026 11:04:00
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.98 kb
#include <bits/stdc++.h>
using namespace std;

int lsb(int x) {
    return x & -x;
}

int main() {
    ifstream cin("stramosi.in");
    ofstream cout("stramosi.out");
    
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n, q; cin >> n >> q;
    int log2n = log2(n) + 1;
    vector<vector<int>> a(log2n + 1, vector<int>(n, -2e9));
    for(int i = 0; i < n; i ++) {
        cin >> a[0][i];
        a[0][i] --;
        if(a[0][i] == -1)
            a[0][i] = -2e9;
    }

    for(int i = 1; i < log2n; i ++) {
        for(int j = 0 ; j < n; j ++) {
            int half = a[i - 1][j];
            if(half == -2e9)
                continue;
            a[i][j] = a[i - 1][half];
        }
    }

    while(q --) {
        int k, x; cin >> x >> k; x --;
        while(k && x != -2e9) {
            x = a[int(log2(lsb(k)))][x];
            k -= lsb(k);
        }
        if(x == -2e9)
            x = -1;
        cout << x + 1 << '\n';
    }
}