Pagini recente » Cod sursa (job #3177618) | Cod sursa (job #2406897) | Cod sursa (job #559585) | Cod sursa (job #821582) | Cod sursa (job #1495316)
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;
ofstream fout("stramosi.out");
ifstream fin("stramosi.in");
const int NMAX = 250050;
int n, m, y, niv_max;
int Niv[NMAX];
vector<int> Graf[NMAX];
bitset<NMAX> Viz;
queue<int> Q;
int bfs(int nod, int stop)
{
while(!Q.empty()) Q.pop();
Viz.reset();
Viz[nod] = 1;
Q.push(nod);
while(!Q.empty()) {
int top = Q.front();
Q.pop();
if(Niv[top] == stop)
return top;
if(stop != -1 && nod && Niv[nod] <= y)
return 0;
for(auto x : Graf[top])
if(!Viz[x]) {
Viz[x] = 1, Q.push(x);
if(stop == -1) {
Niv[x] = Niv[top] + 1;
if(Niv[x] > niv_max) niv_max = Niv[x];
}
}
}
}
int main()
{
fin >> n >> m;
for(int i=1, x; i<=n; i++) {
fin >> x;
Graf[i].push_back(x);
Graf[x].push_back(i);
}
bfs(0, -1);
for(int i=1, x; i<=m; i++) {
fin >> x >> y;
if(Niv[x] - y <= 0) fout << "0\n";
else fout << bfs(x, Niv[x] - y) << '\n';
}
return 0;
}