Pagini recente » Cod sursa (job #2597802) | Cod sursa (job #1486352) | Cod sursa (job #1892332) | Cod sursa (job #2914293) | Cod sursa (job #2222151)
#include <fstream>
#include <iostream>
#include <stack>
#include <tuple>
#include <vector>
#include <algorithm>
using namespace std;
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;
assert(x <= i);
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;
stack<tuple<int, int>> st;
st.emplace(0, 0);
for(int x, mode; !st.empty(); ){
tie(x, mode) = st.top();
st.pop();
if(mode == 0){
st.emplace(x, 1);
rhs[x] = rhs_cur++;
layers[adanc[x]].push_back(x);
for(const auto y : copii[x]){
adanc[y] = adanc[x] + 1;
st.emplace(y, 0); } }
else if(mode == 1 && !copii[x].empty()){
rhs[x] = rhs[copii[x].front()]; } }
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; }