Cod sursa(job #2283105)

Utilizator TooHappyMarchitan Teodor TooHappy Data 14 noiembrie 2018 23:34:01
Problema Stramosi Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.24 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream in("stramosi.in");
ofstream out("stramosi.out");

vector< vector< int > > stramos;

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);

    int n, m; in >> n >> m;

    stramos.resize(n + 1, vector< int >(20));
    for(int i = 1; i <= n; ++i) {
        int s; in >> s;
        if(s == 0) {
            stramos[i][0] = -1;
        } else {
            stramos[i][0] = s;
        }
    }

    for(int j = 1; j < 18; ++j) {
        for(int i = 1; i <= n; ++i) {
            if(stramos[i][j - 1] != -1) {
                stramos[i][j] = stramos[stramos[i][j - 1]][j - 1];
            } else {
                stramos[i][j] = -1;
            }
        }
    }

    for(int i = 1; i <= m; ++i) {
        int q, p; in >> q >> p;

        int tempQ = q, tempP = p;

        for(int k = 20; k >= 0 && tempQ >= 1 && tempP != 0; --k) {
            if((1 << k) > tempP) {
                continue;
            } else {
                tempQ = stramos[tempQ][k];
                tempP -= (1 << k);
            }
        }

        if(tempQ < 1 || tempQ == -1) {
            out << "0\n";
        } else {
            out << tempQ << "\n";
        }
    }

    in.close(); out.close();
 
    return 0;
}