Tree Intersection Query
Practice
5 (2 votes)
Algorithms
Graphs
Binary search
Depth first search
Problem
76% Success 824 Attempts 50 Points 1s Time Limit 256MB Memory 1024 KB Max Code

You are given a tree consisting of \(N\) nodes. You have to answer \(Q\) queries. The \(q^{th}\) query consists of a node \(x_q\) and a set of \(k_q\) distinct nodes \(\{v_1, v_2,\dots, v_{k_q}\}\). The answer to the  \(q^{th}\) query is the number of pairs \((i, j)\) such that \(1 \le i \lt j \le k_q\) and the node \(x_q\) lies on the path between the nodes \(v_i\) and \(v_j\).

Input format

  • The first line of input contains two integers \(N\) denoting the number of nodes in the tree and \(Q\) denoting the number of queries.
  • \(N-1\) lines follow. The \(i^{th}\) line contains two integers \(X_i, Y_i\) denoting an edge between the nodes \(X_i,Y_i\). It is guaranteed that the given nodes and edges form a tree.
  • \(2 \cdot Q\) lines follow. The \((2 \cdot q - 1)\)-th of these lines contains two integers \(x_q, k_q\), and the \(2 \cdot q\) -th line contains \(k_q\) space-separated distinct integers \(\{v_1, v_2,\dots, v_{k_q}\}\).

Output format

For each query, print the answer in a separate line.

Constraints

\(2 \leq N \leq 2\cdot10^5\\ 1 \leq Q \leq 2\cdot10^5 \\ 1 \le X_i \lt Y_i\le N \\ 1 \le k_q, x_q, v_q\le N\\\\ \sum k_q \le 3.5 * 10^5 \\\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
6 votes
Tags:
Depth First SearchGraphsAlgorithms
Points:50
1 votes
Tags:
AlgorithmsGraphsDepth First SearchData Structures
Points:50
8 votes
Tags:
TrieTreeDepth First SearchGraphsAlgorithmsGame Theory