Cod sursa(job #3206786)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 24 februarie 2024 09:23:22
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.1 kb
#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const char sp = ' ';
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const char out[2][4]{ "NO", "YES" };
#define all(a) a.begin(), a.end()
using ll = long long;
ifstream fin("stramosi.in");
ofstream fout("stramosi.out");

const int nmax = 250000;
const int lgmax = 18;
int n, q;
int t[nmax + 5]{ 0 };
int dp[lgmax][nmax + 5]{ 0 };

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n >> q;
    for (int i = 1; i <= n; ++i) {
        fin >> t[i];
        dp[0][i] = t[i];
    }
    for (int p = 1; ; ++p) {
        bool good = false;
        for (int i = 1; i <= n; ++i) {
            dp[p][i] = dp[p - 1][dp[p - 1][i]];
            if (dp[p][i] > 0) {
                good = true;
            }
        }
        if (!good) {
            break;
        }
    }
    while (q--) {
        int u, k;
        fin >> u >> k;
        for (int i = 0; (1 << i) <= k; ++i) {
            if ((k >> i) & 1) {
                u = dp[i][u];
            }
        }
        fout << u << nl;
    }
}