
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Binary Trees With Factors in C++
Suppose we have a list of positive integers; whose value is greater than 1. We will make a binary tree, using these integers, and each number may be used as many times as we want. Each non-leaf node should be the product of its children. So we have to find how many trees can we make? The answer will be returned in modulo 10^9 + 7. So if the input is like [2,4,5,10], then the answer will be 7, as we can make 7 trees like [2], [4], [5], [10], [4,2,2], [10,2,5], [10,5,2]
To solve this, we will follow these steps −
- Define a map dp
- sort the array A, n := size of array A, ret := 0
- for i in range 0 to n – 1
- increase dp[A[i]] by 1
- for j in range 0 to j – 1
- if A[i] mod A[j] = 0, then
- dp[A[i]] := dp[A[i]] + (dp[A[j]] * dp[A[i]] / dp[A[j]])
- if A[i] mod A[j] = 0, then
- ret := ret + dp[A[i]]
- return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; typedef long long int lli; const int MOD = 1e9 + 7; int add(lli a, lli b){ return ((a % MOD) + (b % MOD)) % MOD; } int mul(lli a, lli b){ return ((a % MOD) * (b % MOD)) % MOD; } class Solution { public: int numFactoredBinaryTrees(vector<int>& A) { unordered_map <int, int> dp; sort(A.begin(), A.end()); int n = A.size(); int ret = 0; for(int i = 0; i < n; i++){ dp[A[i]] += 1; for(int j = 0; j < i; j++){ if(A[i] % A[j] == 0){ dp[A[i]] = add(dp[A[i]], mul(dp[A[j]], dp[A[i] / A[j]])); } } ret = add(ret, dp[A[i]]); } return ret; } }; main(){ vector<int> v1 = {2,4,5,10}; Solution ob; cout << (ob.numFactoredBinaryTrees(v1)); }
Input
[2,4,5,10]
Output
7
- Related Articles
- Merge Two Binary Trees in C++
- Unique Binary Search Trees in C++
- Flip Equivalent Binary Trees in C++
- Enumeration of Binary Trees in C++
- Unique Binary Search Trees II in C++
- All Possible Full Binary Trees in C++
- Program to merge two binary trees in C++
- All Elements in Two Binary Search Trees in C++
- Count Balanced Binary Trees of Height h in C++
- Print Common Nodes in Two Binary Search Trees in C++
- Count the Number of Binary Search Trees present in a Binary Tree in C++
- Multidimensional Binary Search Trees
- Binary Search Trees in Data Structures
- Threaded Binary Trees in Data Structure
- Find first non matching leaves in two binary trees in C++

Advertisements