Water Connection Problem | number of houses and number of pipes ; Array rd stores the ending vertex of pipe ; Array wd stores the value of diameters between two pipes ; Array cd stores the starting end of pipe ; arraylist a , b , c are used to store the final output ; Function to perform calculations . ; If a pipe has no ending vertex but has starting vertex i . e is an outgoing pipe then we need to start DFS with this vertex . ; We put the details of component in final output array ; main function ; set the value of the araray to zero
let n , p ; let rd = new Array ( 1100 ) ; let wt = new Array ( 1100 ) ; let cd = new Array ( 1100 ) ; let a = [ ] ; let b = [ ] ; let c = [ ] ; let ans ; function dfs ( w ) { if ( cd [ w ] == 0 ) return w ; if ( wt [ w ] < ans ) ans = wt [ w ] ; return dfs ( cd [ w ] ) ; } function solve ( arr ) { let i = 0 ; while ( i < p ) { let q = arr [ i ] [ 0 ] ; let h = arr [ i ] [ 1 ] ; let t = arr [ i ] [ 2 ] ; cd [ q ] = h ; wt [ q ] = t ; rd [ h ] = q ; i ++ ; } a = [ ] ; b = [ ] ; c = [ ] ; for ( let j = 1 ; j <= n ; ++ j ) if ( rd [ j ] == 0 && cd [ j ] > 0 ) { ans = 1000000000 ; let w = dfs ( j ) ; a . push ( j ) ; b . push ( w ) ; c . push ( ans ) ; } document . write ( a . length + " " ) ; for ( let j = 0 ; j < a . length ; ++ j ) document . write ( a [ j ] + " " + b [ j ] + " " + c [ j ] + " " ) ; } n = 9 ; p = 6 ; for ( let i = 0 ; i < 1100 ; i ++ ) rd [ i ] = cd [ i ] = wt [ i ] = 0 ; let arr = [ [ 7 , 4 , 98 ] , [ 5 , 9 , 72 ] , [ 4 , 6 , 10 ] , [ 2 , 8 , 22 ] , [ 9 , 7 , 17 ] , [ 3 , 1 , 66 ] ] ; solve ( arr ) ;