Cod sursa(job #526508)

Utilizator darrenRares Buhai darren Data 28 ianuarie 2011 15:41:01
Problema Stramosi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.46 kb
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

int N, M;
int pos[250002];
vector<int> V[250002], Qs[250002];
pair<int, int> Q[300002];
vector<int> now, res;
bool S[250002];
int x;

int main()
{
    ifstream fin("stramosi.in");
    ofstream fout("stramosi.out");

    fin >> N >> M;
    for (int i = 1, aux; i <= N; ++i)
    {
        fin >> aux;
        V[aux].push_back(i);
    }
    for (int i = 1; i <= M; ++i)
    {
        fin >> Q[i].first >> Q[i].second;
        Qs[Q[i].first].push_back(Q[i].second);
    }

    x = 0;
    res.push_back(0);
    S[0] = true;

    for (vector<int>::iterator it = V[x].begin(); it != V[x].end(); ++it)
        now.push_back(*it);
    while (!now.empty())
    {
        x = now.back();
        if (S[x])
        {
            res.pop_back();
            now.pop_back();
            continue;
        }

        S[x] = true;
        res.push_back(x);

        for (int i = 0; i < Qs[x].size(); ++i)
        {
            if (Qs[x][i] > res.size() - 1)
                Qs[x][i] = 0;
            else
                Qs[x][i] = res[res.size() - 1 - Qs[x][i]];
        }
        for (vector<int>::iterator it = V[x].begin(); it != V[x].end(); ++it)
            now.push_back(*it);
    }

    for (int i = 1; i <= M; ++i)
    {
        fout << Qs[Q[i].first][pos[Q[i].first]] << '\n';
        ++pos[Q[i].first];
    }

    fin.close();
    fout.close();
}