Cod sursa(job #1090531)

Utilizator harababurelPuscas Sergiu harababurel Data 22 ianuarie 2014 19:38:39
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.92 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];
vector <int> v[nmax];

void build(int 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 > n) return 0;
    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>>dp[0][i]; //practic citesc tatal, = stramosul 2^0
        if(dp[0][i]) v[dp[0][i]].push_back(i);
    }
    for(int i=1; i<=n; i++)
        if(dp[0][i] == 0) build(i);

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

    return 0;
}