Cod sursa(job #2468558)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 5 octombrie 2019 17:29:18
Problema Stramosi Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.09 kb
#include <bits/stdc++.h>
#define MAX 131072

using namespace std;
const int NMAX = 250010;

FILE *IN, *OUT;

int N, M, P;
bool seen[NMAX];
int depth[NMAX], dp[NMAX][19];
vector <int> Gph[NMAX];

int pos, sign, out;
char f[MAX], Out[MAX], str[10];

inline void Read(int &nr){
    sign = 0;
    nr = 0;
    while(f[pos] < '0' || f[pos] > '9'){
        if(f[pos] == '-') sign = 1;
        pos++;
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    while(f[pos] >= '0' && f[pos] <= '9'){
        nr = 10 * nr + f[pos++] - '0';
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    if(sign) nr =- nr;
}

inline void Write_Ch(char ch){
    Out[out++] = ch;
    if(out == MAX)
        fwrite(Out, MAX, 1, OUT), out = 0;
}

inline void Write_Int(int nr){
    int x = 0;
    if(nr < 0) Write_Ch('-'), nr = -nr;
    do{
        str[x++] = nr % 10 + '0';
        nr /= 10;
    } while(nr);
    while(x > 0)
        Write_Ch(str[--x]);
}

void read(){
    int x;
    Read(N); Read(M);
    for(int i = 1; i <= N; i++){
        Read(x);
        Gph[x].push_back(i);
        dp[i][0] = x;
    }
}

void DFS(int node, int val){
    seen[node] = true;
    depth[node] = val;

    for(int i = 1; i <= 18; i++)
        dp[node][i] = dp[dp[node][i - 1]][i - 1];

    for(int i = 0; i < Gph[node].size(); i++)
        if(!seen[Gph[node][i]]) DFS(Gph[node][i], val + 1);
}

int main(){

    IN = fopen("stramosi.in", "r");
    OUT = fopen("stramosi.out", "w");

    read();

    DFS(0, 0);

    int P, Q, ans, x;
    for(int i = 1; i <= M; i++){
        Read(P); Read(Q);
        if(Q == 0){
            Write_Int(P); Write_Ch('\n');
            continue;
        }
        ans = 0; x = depth[P];
        for(int j = 18; j >= 0; j--){
            if(x - depth[dp[P][j]] < Q) P = dp[P][j];
            else if(x - depth[dp[P][j]] == Q){
                ans = dp[P][j];
                break;
            }
        }
        Write_Int(ans); Write_Ch('\n');
    }
    if(out > 0) fwrite(Out, 1, out, OUT);

    return 0;
}