Pagini recente » Cod sursa (job #3209872) | Cod sursa (job #1485124) | Cod sursa (job #2295217) | Cod sursa (job #2065533) | Cod sursa (job #3272057)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("stramosi.in");
ofstream fout ("stramosi.out");
const int DIM = 250001;
vector<int> G[DIM];
int boss[DIM], lvl[DIM], heavy[DIM], idx[DIM], head[DIM], nodes[DIM];
int n, cnt;
int DFS(int);
void HeavyLite(int);
int kth(int, int);
int main() {
int m, x, k;
fin >> n >> m;
for(int i=1; i<=n; ++i) {
fin >> x;
G[x].push_back(i);
}
DFS(0);
/*for(int i=0; i<=n; ++i) {
fout << boss[i] << ' ' << lvl[i] << ' ' << heavy[i] << '\n';
}*/
HeavyLite(0);
while(m--) {
fin >> x >> k;
fout << kth(x, k) << '\n';
}
return 0;
}
int DFS(int x) {
int my_cnt = 1, his_cnt, maxcnt = 0;
for(int y : G[x]) {
boss[y] = x;
lvl[y] = lvl[x] + 1;
his_cnt = DFS(y);
if(his_cnt > maxcnt){
heavy[x] = y;
maxcnt = his_cnt;
}
my_cnt += his_cnt;
}
return my_cnt;
}
void HeavyLite(int x) {
nodes[idx[x] = cnt++] = x;
if(heavy[x]) {
head[heavy[x]] = x;
HeavyLite(heavy[x]);
}
for(int y : G[x]) {
if(y == heavy[x]) continue;
head[y] = y;
HeavyLite(y);
}
}
int kth(int x, int k) {
int lvl_need = lvl[x] - k;
if(lvl_need <= 0) return 0;
while(lvl[head[x]] > lvl_need)
x = boss[head[x]];
return nodes[idx[head[x]] + (lvl_need - lvl[head[x]])];
}