Skip to content
Related Articles

Related Articles

Improve Article

Check if there exists a connected graph that satisfies the given conditions

  • Difficulty Level : Hard
  • Last Updated : 26 Nov, 2019

Given two integers N and K. The task is to find a connected graph with N vertices such that there are exactly K pairs (i, j) where the shortest distance between them is 2. If no such graph exists then print -1.

Note:

  1. The first-line output should be the number of edges(say m) in the graph and the next m lines should contain two numbers represents the edge between the vertices.
  2. In case of multiple answers print any of them.

Examples:

Input: N = 5, K = 3
Output: 7
1 2
1 3
1 4
1 5
3 4
3 5
4 5

Input: N = 5, K = 8
Output: -1



Approach: An N-vertices connected graph has at least N-1 edges. The shortest distance of each pair is equal to 1. So obviously, it is clear that there doesn’t exist a solution if K > N * (N – 1) / 2 – (N – 1) = (N – 1) * (N – 2) / 2.
Conversely, it can be shown that there exists a solution if K ≤ (N – 1) * (N – 2) / 2 by constructing a graph that satisfies the condition. First, let’s consider the graph where each vertex is connected with all the other vertices then the shortest between any two vertices is 1. Now remove any K edges then there exist exactly K such pairs.

Below is the implementation of the above approach:

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the required graph
void connected_graph(int n, int k)
{
    // If no such graph exists
    if (k > (n - 1) * (n - 2) / 2) {
        cout << -1 << endl;
        return;
    }
  
    // Consider edge between all vertices
    bool isEdge[n][n] = {};
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
            isEdge[i][j] = true;
    }
  
    // Remove K vertices
    int cnt = 0;
    for (int i = 1; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (cnt < k) {
                isEdge[i][j] = false;
                cnt++;
            }
        }
    }
  
    // Store all the edges
    vector<pair<int, int> > vec;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (isEdge[i][j])
                vec.emplace_back(i, j);
        }
    }
  
    // Print all the edges
    cout << vec.size() << endl;
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i].first + 1 << " "
             << vec[i].second + 1 << endl;
    }
}
  
// Driver code
int main()
{
    int n = 5, k = 3;
  
    // Function call
    connected_graph(n, k);
  
    return 0;
}

Java




// Java implementation of the 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 find the required graph
static void connected_graph(int n, int k)
{
    // If no such graph exists
    if (k > (n - 1) * (n - 2) / 2
    {
        System.out.println(-1);
        return;
    }
  
    // Consider edge between all vertices
    boolean [][]isEdge = new boolean[n][n];
    for (int i = 0; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++)
            isEdge[i][j] = true;
    }
  
    // Remove K vertices
    int cnt = 0;
    for (int i = 1; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++) 
        {
            if (cnt < k)
            {
                isEdge[i][j] = false;
                cnt++;
            }
        }
    }
  
    // Store all the edges
    Vector<pair> vec = new Vector<>();
    for (int i = 0; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++)
        {
            if (isEdge[i][j])
                vec.add(new pair(i, j));
        }
    }
  
    // Print all the edges
    System.out.println(vec.size());
    for (int i = 0; i < vec.size(); i++) 
    {
        System.out.println(vec.get(i).first + 1
                    " " + (vec.get(i).second + 1));
    }
}
  
// Driver code
public static void main(String[] args) 
{
    int n = 5, k = 3;
  
    // Function call
    connected_graph(n, k);
}
}
  
// This code is contributed by 29AjayKumar

Python3




# Python3 implementation of the approach 
import numpy as np;
  
# Function to find the required graph 
def connected_graph(n, k) : 
  
    # If no such graph exists 
    if (k > (n - 1) * (n - 2) / 2) :
        print(-1) ; 
        return
  
    # Consider edge between all vertices 
    isEdge = np.zeros((n, n)); 
    for i in range(n) :
        for j in range(i + 1, n) :
            isEdge[i][j] = True
  
    # Remove K vertices 
    cnt = 0
    for i in range(1, n) :
        for j in range(i + 1 , n) :
            if (cnt < k) :
                isEdge[i][j] = False
                cnt += 1
  
    # Store all the edges 
    vec = []; 
    for i in range(n) : 
        for j in range(i + 1, n) :
            if (isEdge[i][j]) :
                vec.append([i, j]); 
  
    # Print all the edges 
    print(len(vec)); 
    for i in range(len(vec)) :
        print(vec[i][0] + 1, vec[i][1] + 1); 
  
# Driver code 
if __name__ == "__main__"
  
    n = 5; k = 3;
  
    # Function call 
    connected_graph(n, k); 
  
# This code is contributed by Ankit Rai

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
  
class GFG
{
public class pair
    public int first, second; 
    public pair(int first, int second) 
    
        this.first = first; 
        this.second = second; 
    
}
  
// Function to find the required graph
static void connected_graph(int n, int k)
{
    // If no such graph exists
    if (k > (n - 1) * (n - 2) / 2) 
    {
        Console.WriteLine(-1);
        return;
    }
  
    // Consider edge between all vertices
    bool [,]isEdge = new bool[n, n];
    for (int i = 0; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++)
            isEdge[i, j] = true;
    }
  
    // Remove K vertices
    int cnt = 0;
    for (int i = 1; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++) 
        {
            if (cnt < k)
            {
                isEdge[i, j] = false;
                cnt++;
            }
        }
    }
  
    // Store all the edges
    List<pair> vec = new List<pair>();
    for (int i = 0; i < n; i++) 
    {
        for (int j = i + 1; j < n; j++)
        {
            if (isEdge[i, j])
                vec.Add(new pair(i, j));
        }
    }
  
    // Print all the edges
    Console.WriteLine(vec.Count);
    for (int i = 0; i < vec.Count; i++) 
    {
        Console.WriteLine(vec[i].first + 1 + 
                   " " + (vec[i].second + 1));
    }
}
  
// Driver code
public static void Main(String[] args) 
{
    int n = 5, k = 3;
  
    // Function call
    connected_graph(n, k);
}
}
  
// This code is contributed by 29AjayKumar
Output:
7
1 2
1 3
1 4
1 5
3 4
3 5
4 5

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :