text: Find triplet such that number of nodes connecting these triplets is maximum | C ++ implementation of the approach ; To store the required nodes ; Parent array to retrace the nodes ; Visited array to prevent DFS in direction on Diameter path ; DFS function to find the startnode ; DFS function to find the endnode of diameter and maintain the parent array ; DFS function to find the end node of the Longest Branch to Diameter ; Function to find the required nodes ; To find start node of diameter ; To find end node of diameter ; x is the end node of diameter ; Mark all the nodes on diameter using back tracking ; Find the end node of longest branch to diameter ; Driver code
code: #include <bits/stdc++.h> NEW_LINE #define ll  long long int NEW_LINE #define MAX  100005 NEW_LINE using namespace std ; vector < int > adjacent [ MAX ] ; bool visited [ MAX ] ; int startnode , endnode , thirdnode ; int maxi = -1 , N ; int parent [ MAX ] ; bool vis [ MAX ] ; void dfs ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . size ( ) ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; startnode = u ; } } } void dfs1 ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . size ( ) ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; parent [ adjacent [ u ] [ i ] ] = u ; dfs1 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; endnode = u ; } } } void dfs2 ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent [ u ] . size ( ) ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] && ! vis [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs2 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; thirdnode = u ; } } } void findNodes ( ) { dfs ( 1 , 0 ) ; for ( int i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; maxi = -1 ; dfs1 ( startnode , 0 ) ; for ( int i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; int x = endnode ; vis [ startnode ] = true ; while ( x != startnode ) { vis [ x ] = true ; x = parent [ x ] ; } maxi = -1 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( vis [ i ] ) dfs2 ( i , 0 ) ; } } int main ( ) { N = 4 ; adjacent [ 1 ] . push_back ( 2 ) ; adjacent [ 2 ] . push_back ( 1 ) ; adjacent [ 1 ] . push_back ( 3 ) ; adjacent [ 3 ] . push_back ( 1 ) ; adjacent [ 1 ] . push_back ( 4 ) ; adjacent [ 4 ] . push_back ( 1 ) ; findNodes ( ) ; cout << " ( " << startnode << " , ▁ " << endnode << " , ▁ " << thirdnode << " ) " ; return 0 ; }