Pagini recente » Cod sursa (job #746818) | Cod sursa (job #1485278) | Cod sursa (job #2460872) | Cod sursa (job #2251584) | Cod sursa (job #3272595)
#include <fstream>
#include <vector>
using namespace std;
//ifstream fin ("stramosi.in");
ofstream fout ("stramosi.out");
FILE *in_file = fopen("stramosi.in", "r");
const int DIM = 250001;
const int BUF_SIZE = 1115 * (1 << 10);
vector<int> G[DIM];
int boss[DIM], lvl[DIM], heavy[DIM], idx[DIM], head[DIM], nodes[DIM];
char buf[BUF_SIZE];
int buf_ptr = BUF_SIZE, max_ptr = BUF_SIZE;
int n, cnt;
int DFS(int);
void HeavyLite(int);
int kth(int, int);
int getInt();
int main() {
int m, x, k;
n = getInt();
m = getInt();
for(int i=1; i<=n; ++i) {
x = getInt();
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--) {
x = getInt();
k = getInt();
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]])];
}
int getInt() {
int num = 0;
do {
if(buf_ptr >= max_ptr && max_ptr == BUF_SIZE) {
buf_ptr = 0;
max_ptr = fread(buf, sizeof(buf[0]), BUF_SIZE, in_file);
}
char c = buf[buf_ptr++];
if(c >= '0' && c <= '9') {
num *= 10;
num += c - '0';
}
else break;
} while(1);
return num;
}