Given two positive integers N and K, the task is to construct a simple and connected graph consisting of N vertices with the length of each edge as 1 unit, such that the shortest distance between exactly K pairs of vertices is 2. If it is not possible to construct the graph, then print -1. Otherwise, print the edges of the graph.
Examples:
Input: N = 5, K = 3Â
Output: { { 1, 2 }, { 1, 3}, { 1, 4 }, { 1, 5 }, { 2, 3 }, { 2, 4 }, { 2, 5 } }Â
Explanation:Â
The distance between the pairs of vertices { (3, 4), (4, 5), (3, 5) } is 2.Â
Â
Input: N = 5, K = 8Â
Output: -1
Approach: Follow the steps below to solve the problem:
- Since the graph is simple and connected, Therefore, the maximum possible count of edges, say Max is ((N – 1) * (N – 2)) / 2.
- If K is greater than Max, then print -1.
- Initialize an array, say edges[], to store the edges of the graph.
- Otherwise, first connect all the vertices with 1 and store it in edges[], then connect all the pairs of vertices (i, j) such that i >= 2 and j > i and store it in edges[].
- Finally, print the first ((N – 1) + Max – K ) elements of edges[] array.
Below is the implementation of the above approach:
C++
// C++ program to implement // the above approach Â
#include <iostream> #include <vector> using namespace std; Â
// Function to construct the simple and // connected graph such that the distance // between exactly K pairs of vertices is 2 void constGraphWithCon( int N, int K) { Â
    // Stores maximum possible count     // of edges in a graph     int Max = ((N - 1) * (N - 2)) / 2; Â
    // Base Case     if (K > Max) {         cout << -1 << endl;         return ;     } Â
    // Stores edges of a graph     vector<pair< int , int > > ans; Â
    // Connect all vertices of pairs (i, j)     for ( int i = 1; i < N; i++) {         for ( int j = i + 1; j <= N; j++) {             ans.emplace_back(make_pair(i, j));         }     } Â
    // Print first ((N - 1) + Max - K) elements     // of edges[]     for ( int i = 0; i < (N - 1) + Max - K; i++) {         cout << ans[i].first << " "              << ans[i].second << endl;     } } Â
// Driver Code int main() { Â Â Â Â int N = 5, K = 3; Â Â Â Â constGraphWithCon(N, K); Â
    return 0; } |
C
// C program to implement // the above approach Â
#include <stdio.h> Â
// Function to construct the simple and // connected graph such that the distance // between exactly K pairs of vertices is 2 void constGraphWithCon( int N, int K) { Â
    // Stores maximum possible count     // of edges in a graph     int Max = ((N - 1) * (N - 2)) / 2; Â
    // Base Case     if (K > Max) {         printf ( "-1" );         return ;     } Â
    // Stores count of edges in a graph     int count = 0; Â
    // Connect all vertices of pairs (i, j)     for ( int i = 1; i < N; i++) { Â
        for ( int j = i + 1; j <= N; j++) { Â
            printf ( "%d %d\n" , i, j); Â
            // Update             count++; Â
            if (count == N * (N - 1) / 2 - K)                 break ;         } Â
        if (count == N * (N - 1) / 2 - K)             break ;     } } Â
// Driver Code int main() { Â Â Â Â int N = 5, K = 3; Â Â Â Â constGraphWithCon(N, K); Â
    return 0; } |
Java
// Java program to implement // the above approach import java.util.*; Â
class GFG{ Â Â Â Â Â static class pair { Â Â Â Â int first, second; Â Â Â Â Â Â Â Â Â public pair( int first, int second)Â Â Â Â Â { Â Â Â Â Â Â Â Â this .first = first; Â Â Â Â Â Â Â Â this .second = second; Â Â Â Â }Â Â Â } Â
// Function to construct the simple and connected // graph such that the distance between // exactly K pairs of vertices is 2 static void constGraphWithCon( int N, int K) {          // Stores maximum possible count     // of edges in a graph     int Max = ((N - 1 ) * (N - 2 )) / 2 ; Â
    // Base Case     if (K > Max)     {         System.out.print(- 1 + "\n" );         return ;     } Â
    // Stores edges of a graph     Vector<pair> ans = new Vector<>(); Â
    // Connect all vertices of pairs (i, j)     for ( int i = 1 ; i < N; i++)     {         for ( int j = i + 1 ; j <= N; j++)         {             ans.add( new pair(i, j));         }     } Â
    // Print first ((N - 1) + Max - K) elements     // of edges[]     for ( int i = 0 ; i < (N - 1 ) + Max - K; i++)     {         System.out.print(ans.get(i).first + " " +                          ans.get(i).second + "\n" );     } } Â
// Driver Code public static void main(String[] args) { Â Â Â Â int N = 5 , K = 3 ; Â Â Â Â Â Â Â Â Â constGraphWithCon(N, K); } } Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program to implement # the above approach Â
# Function to construct the simple and # connected graph such that the distance # between exactly K pairs of vertices is 2 def constGraphWithCon(N, K):        # Stores maximum possible count     # of edges in a graph     Max = ((N - 1 ) * (N - 2 )) / / 2          # Base case     if (K > Max ):         print ( - 1 )         return          # Stores edges of a graph     ans = [] Â
    # Connect all vertices of pairs (i, j)     for i in range ( 1 , N):         for j in range (i + 1 , N + 1 ):             ans.append([i, j])                  # Print first ((N - 1) + Max - K) elements     # of edges[]     for i in range ( 0 , (N - 1 ) + Max - K):         print (ans[i][ 0 ], ans[i][ 1 ], sep = " " ) Â
# Driver code if __name__ = = '__main__' : Â Â Â Â Â Â Â Â Â N = 5 Â Â Â Â K = 3 Â Â Â Â Â Â Â Â Â constGraphWithCon(N, K) Â
# This code is contributed by MuskanKalra1 |
C#
// C# program to implement // the above approach using System; using System.Collections.Generic; Â
public class GFG{ Â Â Â Â Â class pair { Â Â Â Â public int first, second; Â Â Â Â Â Â Â Â Â public pair( int first, int second)Â Â Â Â Â { Â Â Â Â Â Â Â Â this .first = first; Â Â Â Â Â Â Â Â this .second = second; Â Â Â Â }Â Â Â } Â
// Function to construct the simple and connected // graph such that the distance between // exactly K pairs of vertices is 2 static void constGraphWithCon( int N, int K) {          // Stores maximum possible count     // of edges in a graph     int Max = ((N - 1) * (N - 2)) / 2; Â
    // Base Case     if (K > Max)     {         Console.Write(-1 + "\n" );         return ;     } Â
    // Stores edges of a graph     List<pair> ans = new List<pair>(); Â
    // Connect all vertices of pairs (i, j)     for ( int i = 1; i < N; i++)     {         for ( int j = i + 1; j <= N; j++)         {             ans.Add( new pair(i, j));         }     } Â
    // Print first ((N - 1) + Max - K) elements     // of edges[]     for ( int i = 0; i < (N - 1) + Max - K; i++)     {         Console.Write(ans[i].first + " " +                          ans[i].second + "\n" );     } } Â
// Driver Code public static void Main(String[] args) { Â Â Â Â int N = 5, K = 3; Â Â Â Â constGraphWithCon(N, K); } } Â
// This code is contributed by 29AjayKumar |
Javascript
<script> Â
// Javascript program to implement // the above approach      class pair {     constructor(first, second)     {         this [0] = first;         this [1] = second;     } } Â
// Function to construct the simple and connected // graph such that the distance between // exactly K pairs of vertices is 2 function constGraphWithCon(N, K) {          // Stores maximum possible count     // of edges in a graph     var Max = ((N - 1) * (N - 2)) / 2; Â
    // Base Case     if (K > Max)     {         document.write(-1 + "<br>" );         return ;     } Â
    // Stores edges of a graph     var ans = []; Â
    // Connect all vertices of pairs (i, j)     for ( var i = 1; i < N; i++)     {         for ( var j = i + 1; j <= N; j++)         {             ans.push([i, j]);         }     } Â
    // Print first ((N - 1) + Max - K) elements     // of edges[]     for ( var i = 0; i < (N - 1) + Max - K; i++)     {         document.write(ans[i][0] + " " +                          ans[i][1] + "<br>" );     } } Â
// Driver Code var N = 5, K = 3; constGraphWithCon(N, K); Â
</script> |
1 2 1 3 1 4 1 5 2 3 2 4 2 5
Â
Time Complexity: O(N2)Â
Auxiliary Space: O(N2)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!