分析
题目要求求出当前点子树dfs遍历时第v个到达的点的编号
那么我们可以直接走dfn序
然后用一个数组记录
那么每次只需要特判加输出即可
时间复杂度:
期望得分:100分
代码
//CF1006E
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#define ll long long
#define cl(x, y) memset((x), (y), sizeof(x))
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define per(i, a, b) for(int i = a; i >= b; i--)
#define de(x) cerr << #x << " = " << x << " "
#define inc_mod(x, y) x = ((x - y) % mod + mod) % mod
#define add_mod(x, y) x = (x + y) % mod
#define lowbit(x) (x & (-x))
#define inf 0x3f3f3f3f
#define mod 998244353
#define rson (x << 1 | 1)
#define lson (x << 1)
using namespace std;
const int maxn = 2e5 + 10;
int nxt[maxn << 1], ed[maxn << 1], head[maxn], cur;
int dfn[maxn], dfn_num, dot[maxn], size[maxn];
int total, u, v, w, opt[maxn], test;
inline void file() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
}
inline void dfs(int now, int pre) {
dfn[now] = ++dfn_num;
dot[dfn_num] = now;
size[now] = 1;
for(int i = head[now]; i; i = nxt[i]) {
if(ed[i] == pre) continue;;
dfs(ed[i], now);
size[now] += size[ed[i]];
}
}
inline void add_edge(int from, int to) {
nxt[++cur] = head[from];
head[from] = cur;
ed[cur] = to;
}
int main() {
// file();
ios::sync_with_stdio(false);
cin >> total >> test;
rep(i, 2, total) cin >> opt[i];
per(i, total, 2) { add_edge(opt[i], i); }
dfs(1, 0);
while(test--) {
cin >> u >> v;
if(size[u] >= v) { cout << dot[dfn[u] + v - 1] << endl; }
else { cout << "-1" << endl; }
}
// fclose(stdin);
// fclose(stdout);
system("pause");
return 0;
} 
京公网安备 11010502036488号