Subtree Queries C++ Solution
Created on: January 25, 2025
Created on: January 25, 2025
Contest Home
Quiz
Coding Problems
Problem
Submissions
Subtree Queries
Accuracy: 0.0%
Submissions: 0
Points: 30
You are given a tree with n vertices, represented by a 2D array g where each row describes an edge between g[i][0] and g[i][1] for 0 <= i < n Additionally, you are provided with qqueries, where each query consists of two integers, x and k. For each query, perform the following steps:
Choose vertex x as the root of the tree.
Compute the size of the subtree for each vertex in the tree (the size of a subtree rooted at a vertex includes the vertex itself and all its descendants).
Sort the sizes of all subtrees in non-decreasing order.
• Find the k-th smallest subtree size in the sorted list.
Your task is to return an array containing the answer to each query.
Examples:
Input: n = 4 g[]] [[2. 1]. [3. 2]. [1. 4]]. q = 3 queries]] =[ [1, 2], [1, 3] . [1, 4]]
Output: [1, 2, 4]
Explanation: Choosing vertex 1 as the root, the subtree sizes in non-decreasing order are [1, 1, 2. 41.
Input: n = 3 g[]= [[2, 1], [2, 3]] . q = 3 queries] = [[1, 2]. [2. 2]. [3.2]]
Output: [2. 1, 2]
Explanation: For the first and third query. choosing vertex 1 and 3 as the root. the subtree sizes in non-decreasing order are [1, 2, 3]. but for second query.
ال
2
3
4
5
A
6
& 7
Q
W
E
R
T
Y code it ibn c++
Below is a straightforward ("naive") C++ implementation that should work correctly for smaller constraints.
Important note on complexity:
This will be too slow for very large and (e.g., ). However, if your input constraints are moderate (e.g., or the total queries are not too large), this approach can pass.
For larger constraints, an advanced “re-rooting” technique or offline data-structure approach would be required. Since the problem statement doesn’t specify maximum limits, here is the clear and direct solution in C++:
cpp#include <bits/stdc++.h> using namespace std; static const int MAXN = 200000; // Adjust if needed, or remove if constraints are small. vector<int> adj[MAXN + 1]; vector<int> subtreeSize; int n, q; // A simple DFS to compute the size of the subtree rooted at `u` (with parent `p`). int dfs_subtree(int u, int p) { int sz = 1; // count current node for(int v : adj[u]) { if(v == p) continue; // don't go back to parent sz += dfs_subtree(v, u); } subtreeSize[u] = sz; return sz; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n; // Read edges // We have n - 1 edges for an n-vertex tree (the statement "0 <= i < n" is a bit confusing, // typically a tree has n-1 edges. Adjust if needed.) for(int i = 0; i < n-1; i++) { int a, b; cin >> a >> b; // Build undirected adjacency adj[a].push_back(b); adj[b].push_back(a); } cin >> q; // We'll answer each query // For each query x, k: // 1) Root the tree at x // 2) DFS to compute subtree sizes for all nodes // 3) Sort the subtree sizes // 4) Output the k-th smallest while(q--) { int x, k; cin >> x >> k; // Prepare subtreeSize array (index from 1..n) subtreeSize.assign(n+1, 0); // Compute subtree sizes with root = x dfs_subtree(x, -1); // Now collect all subtree sizes // (note that subtreeSize[u] is only valid for visited nodes, // but in a tree DFS from root x visits all of them anyway) vector<int> sizes; sizes.reserve(n); for(int i = 1; i <= n; i++) sizes.push_back(subtreeSize[i]); // Sort sort(sizes.begin(), sizes.end()); // k-th smallest is sizes[k-1] in 0-based indexing cout << sizes[k-1] << "\n"; } return 0; }
Reading Input / Building Adjacency
We read (the number of vertices) and then read each of the edges (assuming a proper tree). For each edge , we record the undirected relationship:
Handling Each Query
Each query gives us a root and an integer .
dfs_subtree(x, -1)
to do a depth-first search from , ignoring the parent edge, and accumulate subtree sizes in a global or external array subtreeSize[u]
.subtreeSize[u]
is the size of the subtree rooted at when is considered the overall root.subtreeSize[u]
values for into a vector<int> sizes
and sort them in non-decreasing order.sizes[k-1]
in 0-based indexing.Output
We simply print the answer for each query immediately (or store it to print later).
If you need to handle very large and
You would need an approach more advanced than the naive “DFS + sort” per query. Common strategies might include:
But unless you have tight time constraints and large inputs, the above naive solution is the simplest way to code the logic.