Kth largest node among all directly connected nodes to the given node in an undirected graph | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findKthNode ( int u [ ] , int v [ ] , int n , int val [ ] , int V , int k ) { vector < pair < int , int > > g [ V ] ; for ( int i = 0 ; i < n ; i ++ ) { g [ u [ i ] ] . push_back ( make_pair ( val [ v [ i ] ] , v [ i ] ) ) ; g [ v [ i ] ] . push_back ( make_pair ( val [ u [ i ] ] , u [ i ] ) ) ; } for ( int i = 0 ; i < V ; i ++ ) { if ( g [ i ] . size ( ) > 0 ) sort ( g [ i ] . begin ( ) , g [ i ] . end ( ) ) ; if ( k <= g [ i ] . size ( ) ) printf ( " % d STRNEWLINE " , g [ i ] [ g [ i ] . size ( ) - k ] . second ) ; else printf ( " - 1 STRNEWLINE " ) ; } return ; } int main ( ) { int V = 3 ; int val [ ] = { 2 , 4 , 3 } ; int u [ ] = { 0 , 0 , 1 } ; int v [ ] = { 2 , 1 , 2 } ; int n = sizeof ( u ) / sizeof ( int ) ; int k = 2 ; findKthNode ( u , v , n , val , V , k ) ; return 0 ; }