Cod sursa(job #3291177)

Utilizator zavragiudavid dragoi zavragiu Data 3 aprilie 2025 15:19:03
Problema Stramosi Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <iostream>
#include <string>
#include <bitset>
#include <queue>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <iomanip>
#include <stack>
#include <climits>
#include <unordered_map>
#include <map>
#include <set>
using namespace std;

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

int n, m, dp[18][250001]; /// dp[i][j] = al 2^i-lea stramos al nodului j

int KthAncestor(int k, int nod)
{
    int ans = nod;
    for (int i = 0; (1 << i) <= k; i++)
        if ((1 << i) & k)
            ans = dp[i][ans];
    return ans;
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
        fin >> dp[0][i];
    for (int i = 1; (1 << i) <= n; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = dp[i - 1][dp[i - 1][j]];
    while (m--)
    {
        int nod, k;
        fin >> nod >> k;
        fout << KthAncestor(k, nod) << "\n";
    }
    return 0;
}