Cod sursa(job #2087804)

Utilizator Alex18maiAlex Enache Alex18mai Data 14 decembrie 2017 12:08:35
Problema Stramosi Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.79 kb
#include <fstream>
#include <cmath>

using namespace std;

ifstream cin("stramosi.in");
ofstream cout("stramosi.out");

int dp[250100][20];
int LOG[250100];

int main() {

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++) {
        cin >> dp[i][1];
    }

    for (int i=2; i<=n; i++){
        LOG[i] = LOG[i/2] + 1;
    }

    for (int bit = 2; bit <= LOG[n] + 1; bit++) {
        for (int i = 1; i <= n; i++) {
            dp[i][bit] = dp[dp[i][bit - 1]][bit - 1];
        }
    }

    for (int i = 1; i <= m; i++) {
        int nr, pos;
        cin >> nr >> pos;
        while (pos){
            nr = dp[nr][LOG[pos] + 1];
            pos -= (1 << LOG[pos]);
        }
        cout << nr << '\n';
    }


    return 0;
}