Given an integer k and a tree with n nodes. The task is to count the number of distinct pairs of vertices which have a distance of exactly k.
Input: k = 2
Input: k = 3
Approach: This problem can be solved using dynamic programming. For every vertex v of the tree, we calculate values d[v][lev] (0 <= lev <= k). This value indicates the number of vertices having distance lev from v. Note that d[v] = 0.
Then we calculate the answer. For any vertex v number of pairs will be a product of the number of vertices at level j – 1 and level k – j.
Below is the implementation of the above approach:
- Find the remaining vertices of a square from two given vertices
- Check if a path exists in a tree with K vertices present or are at most at a distance D
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Maximum number of prime factors a number can have with exactly x factors
- Given a n-ary tree, count number of nodes which have more number of children than parents
- Numbers less than N which are product of exactly two distinct prime numbers
- Find two vertices of an isosceles triangle in which there is rectangle with opposite corners (0, 0) and (X, Y)
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Count of distinct graphs that can be formed with N vertices
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors
- Queries to find whether a number has exactly four distinct factors or not
- Find the String having each substring with exactly K distinct characters
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Count number of rotated strings which have more number of vowels in the first half than second half
- Find a permutation such that number of indices for which gcd(p[i], i) > 1 is exactly K
- Check whether a number has exactly three distinct factors or not
- Find k numbers which are powers of 2 and have sum N | Set 1
- Find the count of M character words which have at least one character repeated
- Check if all sub-numbers have distinct Digit product
- Count ways to partition a string such that both parts have equal distinct characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.