Cod sursa(job #3332212)

Utilizator MihneaStoicaMihnea Teodor Stoica MihneaStoica Data 5 ianuarie 2026 09:05:31
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;

#if 0
#define int ll
#define uint ull
#endif

/**
 * Problem: Stramosi
 * URL: https://infoarena.ro/problema/stramosi
 * TL: 350 ms
 * ML: 64 MB
 *
 * Good Luck!
*/

void preinit() {
}

void tc() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> p(17, vector<int>(n + 1));
    for (int i = 1; i <= n; i++) {
        cin >> p[0][i];
    }

    for (int i = 1; i < 17; i++) {
        for (int j = 1; j <= n; j++) {
            p[i][j] = p[i - 1][p[i - 1][j]];
        }
    }

    auto query = [&](int x, int y) -> int {
        for (int j = 16; j >= 0; j--) {
            if (y >= (1 << j)) {
                y -= (1 << j);
                x = p[j][x];
            }
        }
        return x;
    };

    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        cout << query(x, y) << '\n';
    }
}

#define MTC 0
#define FIO 1
#define FN "stramosi"

signed main() {
#if FIO == 1 && !defined(LOCAL)
    (void)freopen(FN ".in", "r", stdin);
    (void)freopen(FN ".out", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    preinit();
#if MTC == 1
    signed tt;
    cin >> tt;
    while (tt--) tc();
#else
    tc();
#endif
    return 0;
}