Approach
Depth-first search
For ABC239 E — Subtree K-th Max, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 58 lines of Python from the credited upstream file abc239_e.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def main():5 import sys6 7 sys.setrecursionlimit(10 ** 8)8 input = sys.stdin.readline9 10 n, q = map(int, input().split())11 x = list(map(int, input().split()))12 graph = [[] for _ in range(n)]13 k = 2014 values = [[] for _ in range(n)]15 16 for _ in range(n - 1):17 ai, bi = map(int, input().split())18 ai -= 119 bi -= 120 21 graph[ai].append(bi)22 graph[bi].append(ai)23 24 def merge(a, b):25 c = sorted(a + b, reverse=True)26 27 if len(c) > k:28 c = c[:k]29 30 return c31 32 def dfs(cur, parent=-1):33 results = [x[cur]]34 35 for to in graph[cur]:36 if to == parent:37 continue38 39 d = dfs(to, cur)40 results = merge(results, d)41 42 values[cur] = results43 return results44 45 dfs(0)46 47 for i in range(q):48 vi, ki = map(int, input().split())49 vi -= 150 ki -= 151 52 ans = values[vi][ki]53 print(ans)54 55 56if __name__ == "__main__":57 main()58