Cod sursa(job #3297789)

Utilizator SebyiIorga Sebastian George Sebyi Data 23 mai 2025 19:49:36
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 0.78 kb
#include <fstream>
using namespace std;

const int MAXN = 250001;
const int LOG = 20;

int up[MAXN][LOG];

int main() {
    ifstream fin("stramosi.in");
    ofstream fout("stramosi.out");

    int N, M;
    fin >> N >> M;

    for (int i = 1; i <= N; ++i) {
        fin >> up[i][0];
    }

    for (int j = 1; j < LOG; ++j) {
        for (int i = 1; i <= N; ++i) {
            if (up[i][j - 1] != 0)
                up[i][j] = up[up[i][j - 1]][j - 1];
            else
                up[i][j] = 0;
        }
    }

    for (int i = 0; i < M; ++i) {
        int q, p;
        fin >> q >> p;
        for (int j = 0; j < LOG; ++j) {
            if (p & (1 << j)) {
                q = up[q][j];
                if (q == 0) break;
            }
        }
        fout << q << '\n';
    }

    return 0;
}