Maximize sum of minimum difference of divisors of nodes in N | C ++ program to maximize the sum of minimum difference of divisors of nodes in an n - ary tree ; Array to store the result at each node ; Function to get minimum difference between the divisors of a number ; Iterate from square root of N to N ; return absolute difference ; DFS function to calculate the maximum sum ; Store the min difference ; Add the maximum of all children to sub [ u ] ; Return maximum sum of node ' u ' to its parent ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sub [ 100005 ] ; int minDivisorDifference ( int n ) { int num1 ; int num2 ; for ( int i = sqrt ( n ) ; i <= n ; i ++ ) { if ( n % i == 0 ) { num1 = i ; num2 = n / i ; break ; } } return abs ( num1 - num2 ) ; } int dfs ( vector < int > g [ ] , int u , int par ) { sub [ u ] = minDivisorDifference ( u ) ; int mx = 0 ; for ( auto c : g [ u ] ) { if ( c != par ) { int ans = dfs ( g , c , u ) ; mx = max ( mx , ans ) ; } } sub [ u ] += mx ; return sub [ u ] ; } int main ( ) { vector < int > g [ 100005 ] ; int edges = 6 ; g [ 18 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 18 ) ; g [ 18 ] . push_back ( 15 ) ; g [ 15 ] . push_back ( 18 ) ; g [ 15 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 15 ) ; g [ 7 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 12 ) ; g [ 12 ] . push_back ( 7 ) ; g [ 12 ] . push_back ( 9 ) ; g [ 9 ] . push_back ( 12 ) ; int root = 18 ; cout << dfs ( g , root , -1 ) ; }