The Wayback Machine - https://web.archive.org/web/20240605145128/https://www.geeksforgeeks.org/maximum-pairs-from-given-graph-where-elements-belong-to-different-connected-component/
Open In App

Maximum pairs from given Graph where elements belong to different Connected Component

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a graph with N vertices numbered from 0 to (N-1) and a matrix edges[][] representing the edges of the graph, the task is to find out the maximum number of pairs that can be formed where each element of a pair belongs to different connected components of the graph.

Examples:

Input: N = 4, edges = {{1, 2}, {2, 3}}
Output: 3
Explanation: Total nodes 4 (from 0 to 3). 
There are 3 possible pairs: {0, 1}, {0, 2} and {0, 3}.
No pair between {1, 2} or {1, 3} or {2, 3} because they belong to the same connected component.
 

graph with given edges

Input: N = 2, edges = {0, 1}
Output: 0
Explanation: All the elements belong to the same connected component.

 

Approach: The problem can be solved by counting the number of connected components and the number of nodes in each connected component. Total N*(N-1)/2 nodes can be formed from the given N nodes. But, to get the required number of pairs subtract the number of pairs that can be formed among the nodes of each connected component. Follow the steps mentioned below:

  • Initiate total as the total number of possible pairs which is N*(N-1)/2.
  • Use DFS to find the different connected components and for each component:
    • Find out the number of nodes in that connected component and store that in a variable (say cnt).
    • Subtract the number of pairs that can be formed by these nodes among themselves i.e. cnt*(cnt – 1)/2.
  • After all the nodes are visited, the remaining value of total is the final answer.

Below is the implementation of the above approach

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// DFS function
void dfs(vector<int> adj[], int src,
         bool visited[], int& cnt)
{
    visited[src] = true;
 
    // Count number of nodes
    // in current component
    cnt++;
    for (auto it : adj[src]) {
        if (!visited[it]) {
            dfs(adj, it, visited, cnt);
        }
    }
}
 
// Function to count total possible pairs
int maxPairs(int N,
             vector<vector<int> >& edges)
{
    vector<int> adj[N];
 
    // Building the adjacency matrix
    for (int i = 0; i < edges.size(); i++) {
        adj[edges[i][0]].push_back(
            edges[i][1]);
        adj[edges[i][1]].push_back(
            edges[i][0]);
    }
 
    // Maximum total pairs
    int total = N * (N - 1) / 2;
 
    // Array to keep track of components
    bool visited[N + 1] = { false };
 
    // Loop to count total possible pairs
    for (int i = 0; i < N; i++) {
        if (visited[i] == false) {
            int cnt = 0;
 
            dfs(adj, i, visited, cnt);
 
            // Subtract pairs from
            // the same connected component
            total -= (cnt * (cnt - 1) / 2);
        }
    }
    return total;
}
 
// Driver code
int main()
{
    int N = 4;
    vector<vector<int> > edges = { { 1, 2 },
                                   { 2, 3 } };
 
    int result = maxPairs(N, edges);
    cout << result;
    return 0;
}


Java




import java.io.*;
import java.util.*;
 
class GFG {
 
  static int count = 0;
 
  // DFS function
  public static void
    dfs(ArrayList<ArrayList<Integer> > adj, int src,
        boolean visited[])
  {
    visited[src] = true;
 
    // Count number of nodes
    // in current component
    count++;
    for (int it : adj.get(src)) {
      if (!visited[it]) {
        dfs(adj, it, visited);
      }
    }
  }
 
  // Function to count total possible pairs
  public static int
    maxPairs(int N, ArrayList<ArrayList<Integer> > edges)
  {
    ArrayList<ArrayList<Integer> > adj
      = new ArrayList<ArrayList<Integer> >();
 
    for (int i = 0; i < N; i++) {
 
      ArrayList<Integer> temp
        = new ArrayList<Integer>();
      adj.add(temp);
    }
 
    // Building the adjacency matrix
    for (int i = 0; i < edges.size(); i++) {
 
      ArrayList<Integer> temp
        = adj.get(edges.get(i).get(0));
      temp.add(edges.get(i).get(1));
      adj.set(edges.get(i).get(0), temp);
 
      temp = adj.get(edges.get(i).get(1));
      temp.add(edges.get(i).get(0));
      adj.set(edges.get(i).get(1), temp);
    }
 
    // Maximum total pairs
    int total = N * (N - 1) / 2;
 
    // Array to keep track of components
 
    boolean[] visited = new boolean[N + 1];
 
    for (int i = 0; i <= N; i++) {
      visited[i] = false;
    }
 
    // Loop to count total possible pairs
    for (int i = 0; i < N; i++) {
      if (visited[i] == false) {
 
        count = 0;
 
        dfs(adj, i, visited);
 
        // Subtract pairs from
        // the same connected component
        total -= (count * (count - 1) / 2);
      }
    }
    return total;
  }
  // Driver code
  public static void main(String[] args)
  {
 
    int N = 4;
    ArrayList<ArrayList<Integer> > edges
      = new ArrayList<ArrayList<Integer> >();
    edges.add(
      new ArrayList<Integer>(Arrays.asList(1, 2)));
    edges.add(
      new ArrayList<Integer>(Arrays.asList(2, 3)));
 
    int result = maxPairs(N, edges);
    System.out.println(result);
  }
}
 
// This code is contributed by Palak Gupta


Python3




# python3 code to implement the approach
 
 
visited = []
cnt = 0
 
# DFS function
 
 
def dfs(adj, src):
    global visited
    global cnt
    visited[src] = True
 
    # Count number of nodes
    # in current component
    cnt += 1
    for it in adj[src]:
        if (not visited[it]):
            dfs(adj, it)
 
 
# Function to count total possible pairs
def maxPairs(N, edges):
    global visited
    global cnt
    adj = [[] for _ in range(N)]
 
    # Building the adjacency matrix
    for i in range(0, len(edges)):
        adj[edges[i][0]].append(edges[i][1])
        adj[edges[i][1]].append(edges[i][0])
 
        # Maximum total pairs
    total = (N * (N - 1)) // 2
 
    # Array to keep track of components
    for i in range(N + 1):
        visited.append(False)
 
        # Loop to count total possible pairs
    for i in range(0, N):
        if (visited[i] == False):
            cnt = 0
 
            dfs(adj, i)
 
            # Subtract pairs from
            # the same connected component
            total -= ((cnt * (cnt - 1)) // 2)
 
    return total
 
 
# Driver code
if __name__ == "__main__":
 
    N = 4
    edges = [[1, 2], [2, 3]]
 
    result = maxPairs(N, edges)
    print(result)
 
    # This code is contributed by rakeshsahni


C#




using System;
using System.Collections.Generic;
class GFG
{
 
  static int count = 0;
 
  // DFS function
  public static void
    dfs(List<List<int>> adj, int src, bool[] visited)
  {
    visited[src] = true;
 
    // Count number of nodes
    // in current component
    count++;
    foreach (int it in adj[src])
    {
      if (!visited[it])
      {
        dfs(adj, it, visited);
      }
    }
  }
 
  // Function to count total possible pairs
  public static int
    maxPairs(int N, List<List<int>> edges)
  {
    List<List<int>> adj = new List<List<int>>();
 
    for (int i = 0; i < N; i++)
    {
 
      List<int> temp = new List<int>();
      adj.Add(temp);
    }
 
    // Building the adjacency matrix
    for (int i = 0; i < edges.Count; i++)
    {
 
      List<int> temp = adj[edges[i][0]];
      temp.Add(edges[i][1]);
      adj[edges[i][0]] = temp;
 
      temp = adj[edges[i][1]];
      temp.Add(edges[i][0]);
      adj[edges[i][1]] = temp;
    }
 
    // Maximum total pairs
    int total = N * (N - 1) / 2;
 
    // Array to keep track of components
    bool[] visited = new bool[N + 1];
 
    for (int i = 0; i <= N; i++)
    {
      visited[i] = false;
    }
 
    // Loop to count total possible pairs
    for (int i = 0; i < N; i++)
    {
      if (visited[i] == false)
      {
 
        count = 0;
 
        dfs(adj, i, visited);
 
        // Subtract pairs from
        // the same connected component
        total -= (count * (count - 1) / 2);
      }
    }
    return total;
  }
   
  // Driver code
  public static void Main()
  {
 
    int N = 4;
    List<List<int>> edges = new List<List<int>>();
    edges.Add(new List<int>());
    edges.Add(new List<int>());
    edges[0].Add(1);
    edges[0].Add(2);
    edges[1].Add(2);
    edges[1].Add(3);
    int result = maxPairs(N, edges);
    Console.Write(result);
  }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript




<script>
      // JavaScript code for the above approach
 
      // DFS function
      function dfs(adj, src,
          visited, cnt) {
          visited[src] = true;
 
          // Count number of nodes
          // in current component
          cnt++;
          for (let it of adj[src]) {
              if (!visited[it]) {
                  dfs(adj, it, visited, cnt);
              }
          }
          return cnt;
      }
 
      // Function to count total possible pairs
      function maxPairs(N,
          edges) {
          let adj = new Array(N).fill([]);
 
          // Building the adjacency matrix
          for (let i = 0; i < edges.length; i++) {
              adj[edges[i][0]].push(
                  edges[i][1]);
              adj[edges[i][1]].push(
                  edges[i][0]);
          }
 
          // Maximum total pairs
          let total = N * (N - 1) / 2;
 
          // Array to keep track of components
          let visited = new Array(N + 1).fill(false)
 
          // Loop to count total possible pairs
          for (let i = 0; i < N; i++) {
              if (visited[i] == false) {
                  let cnt = 0;
 
                  dfs(adj, i, visited, cnt);
 
                  // Subtract pairs from
                  // the same connected component
                  total -= (cnt * (cnt - 1) / 2);
              }
          }
          return total / 2;
      }
 
      // Driver code
      let N = 4;
      let edges = [[1, 2],
      [2, 3]];
 
      let result = maxPairs(N, edges);
      document.write(result);
 
     // This code is contributed by Potta Lokesh
  </script>


 
 

Output

3

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Similar Reads

Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Find the array to which each element in given queries belong along with count of elements
Given an array of pairs arr[][] of length N, and an array queries[] of length M, and an integer R, where each query contains an integer from 1 to R, the task for every queries[i] is to find the set to which it belongs and find the total number of elements of the set. Note: Initially every integer from 1 to R belongs to the distinct set. Examples: I
11 min read
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum
Given an array arr[] consisting of values of N vertices of an initially unconnected Graph and an integer M, the task is to connect some vertices of the graph with exactly M edges, forming only one connected component, such that no cycle can be formed and Bitwise AND of the connected vertices is maximum possible. Examples: Input: arr[] = {1, 2, 3, 4
9 min read
Find the coordinate that does not belong to any square
Given an array arr[] consisting of (4 * N + 1) pairs of coordinates representing the coordinates of the corners of any N squares such that only one coordinate doesn't belong to any square, the task is to find that coordinate that doesn't belong to any square. Examples: Input: N = 2, arr[] = { {0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}, {2, 0},
12 min read
Maximum GCD of all nodes in a connected component of an Undirected Graph
Given an undirected graph consisting of V vertices and a 2d array E[][2] denoting edges between pairs of nodes. Given another array arr[] representing values assigned to each node, the task is to find the maximum GCD among the GCD of all connected components in the graph. Examples: Input: V = 5, E[][2] = {{1, 3}, {2, 3}, {1, 2}}, arr[] = {23, 43, 1
10 min read
Maximum product of a pair of nodes from largest connected component in a Graph
Given an undirected weighted graph G consisting of N vertices and M edges, and two arrays Edges[][2] and Weight[] consisting of M edges of the graph and weights of each edge respectively, the task is to find the maximum product of any two vertices of the largest connected component of the graph, formed by connecting all edges with the same weight.
21 min read
Check if longest connected component forms a palindrome in undirected graph
Given an undirected graph with V vertices and E edges, the task is to check that if the largest connected component of the graph forms a palindrome in the undirected graph. Examples: Input: Output: Longest connected component is Palindrome Explanation: Longest connected component is {5, 15, 5} which forms an palindrome by values. Input: Output: Lon
16 min read
Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph
Given an undirected graph consisting of N vertices and M edges and queries Q[][] of the type {X, Y}, the task is to check if the vertices X and Y are in the same connected component of the Graph. Examples: Input: Q[][] = {{1, 5}, {3, 2}, {5, 2}} Graph: 1-3-4 2 | 5 Output: Yes No No Explanation: From the given graph, it can be observed that the vert
11 min read
All vertex pairs connected with exactly k edges in a graph
Given a directed graph represented as an adjacency matrix and an integer 'k', the task is to find all the vertex pairs that are connected with exactly 'k' edges. Also, find the number of ways in which the two vertices can be linked in exactly k edges. Examples : Input : k = 3 and graph : 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 Output : 1
16 min read
Maximum element in connected component of given node for Q queries
Given an array of pairs arr[][] of length N, and an array queries[] of length M, and an integer R, where queries[i] contain an integer from 1 to R, the task for every queries[i] is to find the maximum element of the connected components of the node with value queries[i]. Note: Initially every integer from 1 to R belongs to the distinct set. Example
11 min read
Article Tags :
Practice Tags :