# Find the Number of Paths of Weight W in a K-ary tree using C++

C++Server Side ProgrammingProgramming

In this article, we'll use C++ to calculate the number of weight W paths in a K-ary tree in this article. We've given a K-ary tree, which is a tree in which each node has K children and each edge has a weight assigned to it, with weights descending from 1 to K from one node to all of its children.

We need to count the cumulative number of paths beginning from the root that have a weight of W and at least one edge with a weight of M. So, here's example −

Input : W = 4, K = 3, M = 2

Output : 6

In the given problem, we will use dp to reduce our time and space complexity. By using memoization, we can make our program much faster and make it usable for larger constraints.

## Approach

In this approach, we will traverse the tree and keep track of the edge that weights at least M if used or not, and the weight is equal to W, so then we increment the answer.

## Input

#include <bits/stdc++.h>
using namespace std;
int solve(int DP[][2], int W, int K, int M, int used){
if (W < 0) // if W becomes less than 0 then return 0
return 0;
if (W == 0) {
if (used) // if used is not zero then return 1
return 1; //as at least one edge of weight M is included
return 0;
}
if (DP[W][used] != -1) // if DP[W][used] is not -1 so that means it has been visited.
return DP[W][used];
for (int i = 1; i <= K; i++) {
if (i >= M)
answer += solve(DP, W - i, K, M, used | 1); // if the condition is true
//then we will change used to 1.
else
answer += solve(DP, W - i, K, M, used);
}
}
int main(){
int W = 3; // weight.
int K = 3; // the number of children a node has.
int M = 2; // we need to include an edge with weight at least 2.
int DP[W + 1][2]; // the DP array which will
memset(DP, -1, sizeof(DP)); // initializing the array with -1 value
cout << solve(DP, W, K, M, 0) << "\n";
return 0;
}

## Output

3

## Explanation of the Above Code

In this approach, keeping track of any edge of weight, M is included at least once or not. Secondly, we calculated the total weight of the path if it becomes equal to W.

We increment the answer by one, mark that path as visited, continue through all the possible paths, and include at least one edge with weight greater than or equal to M.

## Conclusion

In this article, we solve a problem to find the number of paths with weight W in a k-ary tree using dynamic programming in O(W*K) time complexity.

We also learned the C++ program for this problem and the complete approach (Normal and efficient ) by which we solved this problem.

Updated on 24-Nov-2021 07:22:58