DFS序模板题 CF498Div3E
题目链接: http://codeforces.com/contest/1006/problem/E
题意: 给定一棵树, 进行多次查询——查询某节点子树DFS序列的某一项
思路: 求出该树DFS序, 进行查询即可
总结: 第一道DFS序题目.
代码如下:
1 import java.util.*; 2 3 public class Main { 4 static int tot; 5 static ArrayList<Integer>[] g; 6 static int[] in, out, dfs; 7 8 public static void main(String[] args) { 9 Scanner sc = new Scanner(System.in); 10 int n = sc.nextInt(); 11 int m = sc.nextInt(); 12 in = new int[n + 1]; 13 out = new int[n + 1]; 14 dfs = new int[n + 1]; 15 g = new ArrayList[n + 1]; 16 for (int i = 1; i <= n; i++) { 17 g[i] = new ArrayList<>(); 18 } 19 for (int i = 2; i <= n; i++) { 20 int t = sc.nextInt(); 21 g[i].add(t); 22 g[t].add(i); 23 } 24 dfs(1, 0); 25 for (int i = 0; i < m; i++) { 26 int u = sc.nextInt(), k = sc.nextInt(); 27 k--; 28 if (out[u] - in[u] >= k) { 29 System.out.println(dfs[in[u] + k]); 30 } else { 31 System.out.println(-1); 32 } 33 } 34 } 35 36 public static void dfs(int u, int from) { 37 in[u] = ++tot; 38 dfs[tot] = u; 39 for (int i = 0; i < g[u].size(); i++) { 40 if (g[u].get(i) != from) { 41 dfs(g[u].get(i), u); 42 } 43 } 44 out[u] = tot; 45 } 46 47 }

浙公网安备 33010602011771号