Cod sursa(job #496652)

Utilizator chibicitiberiuChibici Tiberiu chibicitiberiu Data 30 octombrie 2010 10:40:33
Problema Stramosi Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.44 kb
#define INPUT "stramosi.in"
#define OUTPUT "stramosi.out"
#define DEBUG 0

#if DEBUG == 1
#include <iostream>
#endif
#include <fstream>
using namespace std;

int *A, N;
int **B;

inline int Compute(int i)
{
    int siz;
    if (A[i] == 0) {
        B[i] = new int[1];
        B[i][0] = 1;
        B[i][1] = 0;
        return 3;
    }
    
    siz = Compute(A[i]);
    B[i] = new int[siz];
    B[i][0] = siz-1;
    B[i][1] = A[i];
    for (int j=2; j < siz-1; j++)
        B[i][j] = B[A[i]][j-1];
    B[i][siz-1] = 0;

    return siz+1;
}

inline int FindNth(int n, int i)
{
    if (B[i] == 0) Compute(i);

    if (B[i][0]-1 < n) return 0;
    else return B[i][n];
}

int main() {
    int Questions;

    ifstream in(INPUT);
    ofstream out(OUTPUT);

    in>>N>>Questions;
    A = new int[N+2];
    for (int i=1; i <= N; i++)
        in>>A[i];

    B = new int* [N+2]; memset(B, 0, N*sizeof(int*));

    int ii, nn;
    for (; Questions > 0; --Questions)
    {
        in>>ii>>nn;
        out<<FindNth(nn, ii)<<endl;
    }

#if DEBUG == 1
    for (int i=1; i < N+1; i++)
    {
        cout<<i<<">\t";
        if (B[i] == 0) cout<<"Not calculated.";
        else {
            cout<<"Size: "<<B[i][0]<<"  Elements: ";
            for (int j=1; j <= B[i][0]; j++)
                cout<<B[i][j]<<" ";
        }
        cout<<endl;
    }
#endif
    
    in.close();
    out.close();
    delete[] A;
    for (int i=0; i < N+2; i++) delete[] B[i];
    delete[] B;
    return 0;
}