Cod sursa(job #3272057)

Utilizator cinavalptopscalaCont laptop in scoala cinavalptopscala Data 28 ianuarie 2025 11:12:36
Problema Stramosi Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.4 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("stramosi.in");
ofstream fout ("stramosi.out");

const int DIM = 250001;

vector<int> G[DIM];
int boss[DIM], lvl[DIM], heavy[DIM], idx[DIM], head[DIM], nodes[DIM];
int n, cnt;

int DFS(int);
void HeavyLite(int);
int kth(int, int);

int main() {
    int m, x, k;
    fin >> n >> m;
    for(int i=1; i<=n; ++i) {
        fin >> x;
        G[x].push_back(i);
    }
    DFS(0);
    /*for(int i=0; i<=n; ++i) {
        fout << boss[i] << ' ' << lvl[i] << ' ' << heavy[i] << '\n';
    }*/
    HeavyLite(0);
    while(m--) {
        fin >> x >> k;
        fout << kth(x, k) << '\n';
    }
    return 0;
}

int DFS(int x) {
    int my_cnt = 1, his_cnt, maxcnt = 0;
    for(int y : G[x]) {
        boss[y] = x;
        lvl[y] = lvl[x] + 1;
        his_cnt = DFS(y);
        if(his_cnt > maxcnt){
            heavy[x] = y;
            maxcnt = his_cnt;
        }
        my_cnt += his_cnt;
    }
    return my_cnt;
}
void HeavyLite(int x) {
    nodes[idx[x] = cnt++] = x;
    if(heavy[x]) {
        head[heavy[x]] = x;
        HeavyLite(heavy[x]);
    }
    for(int y : G[x]) {
        if(y == heavy[x]) continue;
        head[y] = y;
        HeavyLite(y);
    }
}
int kth(int x, int k) {
    int lvl_need = lvl[x] - k;
    if(lvl_need <= 0) return 0;
    while(lvl[head[x]] > lvl_need)
        x = boss[head[x]];
    return nodes[idx[head[x]] + (lvl_need - lvl[head[x]])];
}