Problem Statement:
You are given an integer N denoting number of nodes in that tree. Now, you need to count, how many distinct paths are there in the tree, such that, minimum node value in that path is greater than or equal to k.
Input format:
- First line contains total number of nodes
Nin that tree and a positive integer valueK. - Next
N-1lines contain a pair of integersu, v(values are not comma seperated), which denote that there is an edge between nodeuandv, in the tree.
Example:
Input:
4 2
1 2
2 3
3 4
Expected Output:
3
Edit: I am not able to think of how to approach this problem. So, please provide me with a hint, so that i can further try implementing it. I'll be greatful to even the slightest help.
Update:
1 <= N <= 10^5
1 <= u,v <= N
1 <= K <= 10^6
A naive approach to such a problem will not pass under any cirumstances. The complexity of the solution should be either O(n**2) or O(nlogn).
This problem can be solved using Dynamic Programming on Trees, you can read about it here https://www.geeksforgeeks.org/dynamic-programming-trees-set-2/.
Let's split the problem into two parts, the first one is to find the number of paths that are valid in the subtree of a node
u. The second part is to find the answer for the nodeuif we do not consider its subtree but going to it's parent and so on.Let us consider 1 as the root of the tree.
Now for solving the first part, we will make an array
in[]in which we will store the the number of paths in the subtree of nodeusoin[u]will represent the number of valid paths starting from the nodeuand visiting its subtree. To compute this array we can run a simple dfs as follows :For solving the second part we need an array
out[]without[u]being the number of paths that are valid if we do not consider the subtree ofuwhich is going to the parent ofuand so on.lets call the parent of
uP[u]. To computeout[u]we will rely onp[u].out[i]is number of valid paths if we go top[u], and what we can do once we reachp[u]is either go through its subtree (excluding the brach ofuof course) or visitp[p[u]](the parent of parent ofu) soout[u]is(out[p[u]] + 1) + (in[p[u]] - in[u] - 1).To find the answer just sum all
out[u] + in[u]for all the nodes and divide by 2 because each path was computed twice.complexity O(V+E)