AcWing 4310. 树的DFS
原题链接
困难
作者:
bakanoko
,
2025-03-24 22:28:24
·广东
,
所有人可见
,
阅读 2
题目规定搜索顺序,使用List数组按顺序存邻边,dfs过程中得到搜索序列和每个节点的子节点数(一开始想把每个节点的所有子节点存下来后来发现不需要,只要子节点数>=k就说明该点在子树中)
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException {
Solution s = new Solution();
String[] ss = read.readLine().split(" ");
int n = Integer.valueOf(ss[0]);
int q = Integer.valueOf(ss[1]);
s.solve (n, q, read, out);
out.flush();
}
}
class Solution{
public Solution(){}
static int N = (int)2e5 + 3;
int n, q;
boolean[] has = new boolean[N];
List<List<Integer>> node = new ArrayList<>();
List<Integer> path = new ArrayList<>();
Map<Integer, Integer> son = new HashMap<>();
int dfs (int u) {
has[u] = true;
int sum = 1;
for (int i = 1; i < node.get(u).size(); i++) {
int v = node.get(u).get(i);
if (!has[v]) {
path.add(v);
int s = dfs(v);
sum += s;
}
}
son.put(u, sum);
return sum;
}
public void solve (int n, int q, BufferedReader read, PrintWriter out) throws IOException {
this.n = n;
this.q = q;
for (int i = 0; i < N; i++) {
List<Integer> tmp = new ArrayList<>();
tmp.add(i);
node.add(new ArrayList<>(tmp));
}
String[] ss = read.readLine().split(" ");
for (int v = 2; v <= n; v++) {
int u = Integer.valueOf(ss[v-2]);
node.get(u).add(v);
}
path.add(1);
dfs(1);
Map<Integer, Integer> pos = new HashMap<>();
for (int i = 0; i < path.size(); i++) {
pos.put(path.get(i), i);
}
for (int i = 0; i < q; i++) {
String[] ss1 = read.readLine().split(" ");
int u = Integer.valueOf(ss1[0]);
int k = Integer.valueOf(ss1[1]);
int p = pos.get(u) + k - 1;
if (son.get(u) >= k) out.println(path.get(p));
else out.println(-1);
}
out.flush();
}
}
class Test{
public Test(){};
public void test () {
}
}