Pagini recente » Infoarena Monthly 2012 - Runda 8, Clasament | Cod sursa (job #809880) | Cod sursa (job #1942903) | Cod sursa (job #3128865) | Cod sursa (job #526508)
Cod sursa(job #526508)
#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();
}