Kth largest node among all directly connected nodes to the given node in an undirected graph | C # implementation of the approach ; pair class ; Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the Vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { class pair { public int first , second ; public pair ( int a , int b ) { first = a ; second = b ; } } class sortHelper : IComparer { int IComparer . Compare ( object a , object b ) { pair first = ( pair ) a ; pair second = ( pair ) b ; return first . first - second . first ; } } static void findKthNode ( int [ ] u , int [ ] v , int n , int [ ] val , int V , int k ) { ArrayList g = new ArrayList ( ) ; for ( int i = 0 ; i < V ; i ++ ) g . Add ( new ArrayList ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { ( ( ArrayList ) g [ u [ i ] ] ) . Add ( new pair ( val [ v [ i ] ] , v [ i ] ) ) ; ( ( ArrayList ) g [ v [ i ] ] ) . Add ( new pair ( val [ u [ i ] ] , u [ i ] ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { if ( ( ( ArrayList ) g [ i ] ) . Count > 0 ) { ArrayList tmp = ( ArrayList ) g [ i ] ; tmp . Sort ( new sortHelper ( ) ) ; g [ i ] = tmp ; } if ( k <= ( ( ArrayList ) g [ i ] ) . Count ) Console . Write ( ( ( pair ) ( ( ArrayList ) g [ i ] ) [ ( ( ArrayList ) g [ i ] ) . Count - k ] ) . second + " STRNEWLINE " ) ; else Console . Write ( " - 1 STRNEWLINE " ) ; } return ; } public static void Main ( string [ ] args ) { int V = 3 ; int [ ] val = { 2 , 4 , 3 } ; int [ ] u = { 0 , 0 , 1 } ; int [ ] v = { 2 , 1 , 2 } ; int n = u . Length ; int k = 2 ; findKthNode ( u , v , n , val , V , k ) ; } }