Cod sursa(job #1362994)

Utilizator gapdanPopescu George gapdan Data 26 februarie 2015 17:31:24
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.48 kb
#include <cstdio>
#include <vector>
#include <stack>
#define NMAX 260005
#define MMAX 310005

using namespace std;

struct mmm
{
    int x,y;
}q[MMAX];

int n, m, k, x;
int st[NMAX], tata[NMAX], niv[NMAX], poz[MMAX];
bool viz[NMAX];
vector<int>v[NMAX],sol[NMAX],a[NMAX];
stack<int>sti;

void DFS(int nod)
{
    int i;
    sti.push(nod);
    while(!sti.empty())
    {
        x=sti.top();
        sti.pop();
        viz[x]=1;
        niv[x] = niv[tata[x]] + 1;
        st[niv[x]]=x;
        k=niv[x];

        if (a[x].size() != 0)
        {
            for(i = 0; i < a[x].size() ;++i)
                if (k - a[x][i] >= 0) sol[x].push_back(st[k - a[x][i]]);
                    else sol[x].push_back(0);
        }

        for(i = 0; i < v[x].size(); ++i)
            if (viz[v[x][i]] == 0) sti.push(v[x][i]);
    }
}

int main()
{
    freopen("stramosi.in","r",stdin);
    freopen("stramosi.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d",&x);
        if (x != 0)
        {
            v[x].push_back(i);
            tata[i] = x;
        }
    }

    for(int i = 1; i <= m; ++i)
    {
        scanf("%d%d",&q[i].x,&q[i].y);
        a[q[i].x].push_back(q[i].y);
        poz[i] = a[q[i].x].size() - 1;
    }

    for(int i = 1; i <= n; ++i)
    {
        if (tata[i] == 0) DFS(i);
    }

    for(int i = 1; i <= m; ++i)
        printf("%d\n",sol[q[i].x][poz[i]]);

    return 0;
}