Cod sursa(job #1090520)

Utilizator harababurelPuscas Sergiu harababurel Data 22 ianuarie 2014 19:33:22
Problema Stramosi Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define nmax 250005
#define logmax 20
using namespace std;

int n, m, x, p;
int dp[logmax][nmax], father[nmax];
vector <int> v[nmax];

void build(int x) {
    dp[0][x] = father[x];
    for(int i=1; (1<<i)<=n; i++)
        dp[i][x] = dp[i-1][ dp[i-1][x] ];

    for(int i=0; i<int(v[x].size()); i++) build(v[x][i]);
}

int find(int p, int x) {
    if(p==0) return x;
    int i = 0;

    while((1<<(i+1)) <= p) i++;
    return find(p - (1<<i), dp[i][x]);
}

int main() {
    ifstream f("stramosi.in");
    ofstream g("stramosi.out");

    f>>n>>m;
    for(int i=1; i<=n; i++) {
        f>>x;
        father[i] = x;
        if(x) v[x].push_back(i);
    }
    for(int i=1; i<=n; i++)
        if(father[i] == 0) build(i);

    while(m--)
        f>>x>>p,
        g<<find(min(p, n), x)<<"\n";

    return 0;
}