Pagini recente » Cod sursa (job #2449809) | Atasamentele paginii dedicatie_speciala2 | Cod sursa (job #812048) | Cod sursa (job #1776526) | Cod sursa (job #1596425)
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
static void dfs(const int cur, const vector<vector<int>>& copii, vector<int>& adanc,
vector<int>& rhs, vector<vector<int>>& layers, int& rhs_cur){
rhs[cur] = rhs_cur++;
layers[adanc[cur]].push_back(cur);
for(const auto next : copii[cur]){
adanc[next] = adanc[cur] + 1;
dfs(next, copii, adanc, rhs, layers, rhs_cur);
rhs[cur] = rhs[next]; } }
int main(){
ifstream f("stramosi.in");
ofstream g("stramosi.out");
int n, m;
f >> n >> m;
static vector<vector<int>> copii(n+1);
for(int i = 1, x; i <= n; ++i){
f >> x;
copii[x].push_back(i); }
static vector<int> adanc(n+1, 0), rhs(n+1, 0);
static vector<vector<int>> layers(n+1);
int rhs_cur = 0;
dfs(0, copii, adanc, rhs, layers, rhs_cur);
auto cmp = [&](const int a, const int b){
return rhs[a] < rhs[b]; };
for(int i = 0, x, d; i < m; ++i){
f >> x >> d;
const auto& layer = layers[max(adanc[x] - d, 0)];
g << *lower_bound(begin(layer), end(layer), x, cmp) << '\n'; }
return 0; }