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]])
    • ret := ret + dp[A[i]]
  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#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

Updated on: 04-May-2020

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements