# Python program for the above approach from typing import List, Dict, Tuple def add(u: int, v: int, adj: List[List[int]]) -> None: adj[u].append(v) adj[v].append(u) # Function to find subtree size # of every vertex using dfsSize() def dfs_size(v: int, p: int, adj: List[List[int]], size: List[int]) -> None: size[v] = 1 # Traverse dfsSize recursively for u in adj[v]: if u != p: dfs_size(u, v, adj, size) size[v] += size[u] # Function to implement DFS Traversal def dfs(v: int, p: int, adj: List[List[int]], num: List[int], map: List[Dict[int,int]], qv: List[List[int]], ans: Dict[Tuple[int,int],bool], size: List[int]) -> None: mx = -1 big_u = -1 # Find adjacent vertex with # maximum size for u in adj[v]: if u != p: dfs(u, v, adj, num, map, qv, ans, size) if size[u] > mx: mx = size[u] big_u = u # Passing referencing if big_u != -1: map[v] = map[big_u] else: # If no adjacent vertex # present initialize map[v] map[v] = {} # Update frequency of current number map[v][num[v]] = map[v].get(num[v], 0) + 1 # Add all adjacent vertices # maps to map[v] for u in adj[v]: if u != big_u and u != p: for key, value in map[u].items(): map[v][key] = value + map[v].get(key, 0) # Store all queries related # to vertex v for freq in qv[v]: ans[(v, freq)] = freq in map[v].values() # Function to find answer for # each queries def solve_query(queries: List[Tuple[int,int]], N: int, q: int, adj: List[List[int]], num: List[int]) -> List[bool]: # Add all queries to qv # where i<qv[v].size() qv = [[] for i in range(N+1)] for p in queries: qv[p[0]].append(p[1]) # Get sizes of all subtrees size = [0]*(N+1) # calculate size[] dfs_size(1, 0, adj, size) # Map will be used to store # answers for current vertex # on dfs map = [None]*(N+1) # To store answer of queries ans = {} # DFS Call dfs(1, 0, adj, num, map, qv, ans, size) # Print answer for each query return [ans[p] for p in queries] if __name__ == '__main__': N = 8 # To store edges adj = [[] for i in range(N+1)] # Given edges (root=1) add(1, 2, adj) add(1, 3, adj) add(2, 4, adj) add(2, 5, adj) add(5, 8, adj) add(5, 6, adj) add(6, 7, adj) # Store number given to vertices # set num[0]=-1 because # there is no vertex 0 num = [-1, 11, 2, 7, 1, -3, -1, -1, -3] # Queries q = 3 # Given Queries queries = [(2,3), (5,2), (7,1)] # Function Call ans = solve_query(queries, N, q, adj, num) for val in ans: print(val) # The code is contributed by Arushi Goel.