📜  使有向图强连通所需的最小边

📅  最后修改于: 2021-10-25 05:01:39             🧑  作者: Mango

给定一个N个顶点和M 个边组成的有向,任务是找到使给定图成为强连接所需的最小边数。

例子:

方法:
对于强连通图,每个顶点的入度和出度必须至少为1 。因此,为了使图强连通,每个顶点必须有一个输入边和一个输出边。使图强连接所需的传入边和传出边的最大数量是使其强连接所需的最小边。
请按照以下步骤解决问题:

  • 使用 DFS 查找图的每个顶点的入度和出度数。
  • 如果顶点的入度或出度大于1 ,则将其视为仅1
  • 计算给定图的总入度和出度
  • 使图强连接所需的最小边数由max(N-totalIndegree, N-totalOutdegree) 给出。
  • 打印最小边的计数作为结果。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Perform DFS to count the in-degree
// and out-degree of the graph
void dfs(int u, vector adj[], int* vis, int* inDeg,
         int* outDeg)
{
    // Mark the source as visited
    vis[u] = 1;
 
 
    // Traversing adjacent nodes
    for (auto v : adj[u])
    {
        // Mark out-degree as 1
        outDeg[u] = 1;
        // Mark in-degree as 1
        inDeg[v] = 1;
 
        // If not visited
        if (vis[v] == 0)
        {
            // DFS Traversal on
            // adjacent vertex
            dfs(v, adj, vis, inDeg, outDeg);
        }
    }
}
 
// Function to return minimum number
// of edges required to make the graph
// strongly connected
int findMinimumEdges(int source[], int N, int M, int dest[])
{
    // For Adjacency List
    vector adj[N + 1];
 
    // Create the Adjacency List
    for (int i = 0; i < M; i++)
    {
        adj].push_back(dest[i]);
    }
 
    // Initialize the in-degree array
    int inDeg[N + 1] = { 0 };
 
    // Initialize the out-degree array
    int outDeg[N + 1] = { 0 };
 
    // Initialize the visited array
    int vis[N + 1] = { 0 };
 
    // Perform DFS to count in-degrees
    // and out-degreess
    dfs(1, adj, vis, inDeg, outDeg);
 
    // To store the result
    int minEdges = 0;
 
    // To store total count of in-degree
    // and out-degree
    int totalIndegree = 0;
    int totalOutdegree = 0;
 
    // Find total in-degree
    // and out-degree
    for (int i = 1; i <= N; i++)
    {
        if (inDeg[i] == 1)
            totalIndegree++;
        if (outDeg[i] == 1)
            totalOutdegree++;
    }
 
    // Calculate the minimum
    // edges required
    minEdges = max(N - totalIndegree, N - totalOutdegree);
 
    // Return the minimum edges
    return minEdges;
}
 
// Driver Code
int main()
{
    int N = 5, M = 5;
 
    int source[] = { 1, 3, 1, 3, 4 };
    int destination[] = { 2, 2, 3, 4, 5 };
 
    // Function call
    cout << findMinimumEdges(source, N, M, destination);
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
  
// Perform DFS to count the
// in-degree and out-degree
// of the graph
static void dfs(int u, Vector adj[],
                int[] vis, int[] inDeg,
         int[] outDeg)
{
  // Mark the source
  // as visited
  vis[u] = 1;
  
  // Traversing adjacent nodes
  for (int v : adj[u])
  {
    // Mark out-degree as 1
      outDeg[u] = 1;
    // Mark in-degree as 1
      inDeg[v] = 1;
     
    // If not visited
    if (vis[v] == 0)
    {
  
      // DFS Traversal on
      // adjacent vertex
      dfs(v, adj, vis,
          inDeg, outDeg);
    }
  }
}
  
// Function to return minimum
// number of edges required
// to make the graph strongly
// connected
static int findMinimumEdges(int source[],
                            int N, int M,
                            int dest[])
{
  // For Adjacency List
  @SuppressWarnings("unchecked")
  Vector []adj =
         new Vector[N + 1];
   
  for (int i = 0; i < adj.length; i++)
    adj[i] = new Vector();
   
  // Create the Adjacency List
  for (int i = 0; i < M; i++)
  {
    adj].add(dest[i]);
  }
  
  // Initialize the in-degree array
  int inDeg[] = new int[N + 1];
  
  // Initialize the out-degree array
  int outDeg[] = new int[N + 1];
  
  // Initialize the visited array
  int vis[] = new int[N + 1];
  
  // Perform DFS to count
  // in-degrees and out-degreess
  dfs(1, adj, vis, inDeg, outDeg);
  
  // To store the result
  int minEdges = 0;
  
  // To store total count of
  // in-degree and out-degree
  int totalIndegree = 0;
  int totalOutdegree = 0;
  
  // Find total in-degree
  // and out-degree
  for (int i = 1; i <= N; i++)
  {
    if (inDeg[i] == 1)
      totalIndegree++;
    if (outDeg[i] == 1)
      totalOutdegree++;
  }
  
  // Calculate the minimum
  // edges required
  minEdges = Math.max(N - totalIndegree,
                      N - totalOutdegree);
  
  // Return the minimum edges
  return minEdges;
}
  
// Driver Code
public static void main(String[] args)
{
  int N = 5, M = 5;
  int source[] = {1, 3, 1, 3, 4};
  int destination[] = {2, 2, 3, 4, 5};
  
  // Function call
  System.out.print(findMinimumEdges(source,
                                    N, M,
                                    destination));
}
}


Python3
# Python3 program to implement
# the above approach
  
# Perform DFS to count the in-degree
# and out-degree of the graph
def dfs(u, adj, vis,inDeg, outDeg):
 
    # Mark the source as visited
    vis[u] = 1;
  
    # Traversing adjacent nodes
    for v in adj[u]:
        # Mark out-degree as 1
        outDeg[u] = 1;
        # Mark in-degree as 1
        inDeg[u] = 1;
         
        # If not visited
        if (vis[v] == 0):
  
            # DFS Traversal on
            # adjacent vertex
            dfs(v, adj, vis,
                inDeg, outDeg)
 
# Function to return minimum
# number of edges required
# to make the graph strongly
# connected
def findMinimumEdges(source, N,
                     M, dest):
 
    # For Adjacency List
    adj = [[] for i in range(N + 1)]
  
    # Create the Adjacency List
    for i in range(M):
        adj].append(dest[i]);
     
  
    # Initialize the in-degree array
    inDeg = [0 for i in range(N + 1)]
  
    # Initialize the out-degree array
    outDeg = [0 for i in range(N + 1)]
  
    # Initialize the visited array
    vis = [0 for i in range(N + 1)]
  
    # Perform DFS to count in-degrees
    # and out-degreess
    dfs(1, adj, vis, inDeg, outDeg);
  
    # To store the result
    minEdges = 0;
  
    # To store total count of
    # in-degree and out-degree
    totalIndegree = 0;
    totalOutdegree = 0;
  
    # Find total in-degree
    # and out-degree
    for i in range(1, N):   
        if (inDeg[i] == 1):
            totalIndegree += 1;
        if (outDeg[i] == 1):
            totalOutdegree += 1;   
  
    # Calculate the minimum
    # edges required
    minEdges = max(N - totalIndegree,
                   N - totalOutdegree);
  
    # Return the minimum edges
    return minEdges;
 
# Driver code
if __name__ == "__main__":
     
    N = 5
    M = 5
  
    source = [1, 3, 1, 3, 4]
    destination = [2, 2, 3, 4, 5]
  
    # Function call
    print(findMinimumEdges(source, N,
                           M, destination))
     
# This code is contributed by rutvik_56


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Perform DFS to count the
// in-degree and out-degree
// of the graph
static void dfs(int u, List []adj,
                int[] vis, int[] inDeg,
                int[] outDeg)
{
     
    // Mark the source
    // as visited
    vis[u] = 1;
     
    // Traversing adjacent nodes
    foreach (int v in adj[u])
    {
          // Mark out-degree as 1
        outDeg[u] = 1;
        // Mark in-degree as 1
        inDeg[v] = 1;
       
        // If not visited
        if (vis[v] == 0)
        {           
            // DFS Traversal on
            // adjacent vertex
            dfs(v, adj, vis,
                inDeg, outDeg);
        }
    }
}
 
// Function to return minimum
// number of edges required
// to make the graph strongly
// connected
static int findMinimumEdges(int []source,
                            int N, int M,
                            int []dest)
{
     
    // For Adjacency List
    List []adj = new List[N + 1];
     
    for(int i = 0; i < adj.Length; i++)
        adj[i] = new List();
     
    // Create the Adjacency List
    for(int i = 0; i < M; i++)
    {
        adj].Add(dest[i]);
    }
     
    // Initialize the in-degree array
    int []inDeg = new int[N + 1];
     
    // Initialize the out-degree array
    int []outDeg = new int[N + 1];
     
    // Initialize the visited array
    int []vis = new int[N + 1];
     
    // Perform DFS to count
    // in-degrees and out-degreess
    dfs(1, adj, vis, inDeg, outDeg);
     
    // To store the result
    int minEdges = 0;
     
    // To store total count of
    // in-degree and out-degree
    int totalIndegree = 0;
    int totalOutdegree = 0;
     
    // Find total in-degree
    // and out-degree
    for (int i = 1; i <= N; i++)
    {
        if (inDeg[i] == 1)
            totalIndegree++;
        if (outDeg[i] == 1)
            totalOutdegree++;
    }
     
    // Calculate the minimum
    // edges required
    minEdges = Math.Max(N - totalIndegree,
                        N - totalOutdegree);
     
    // Return the minimum edges
    return minEdges;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 5, M = 5;
    int []source = { 1, 3, 1, 3, 4 };
    int []destination = { 2, 2, 3, 4, 5 };
     
    // Function call
    Console.Write(findMinimumEdges(source,
                                   N, M,
                                   destination));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出
2

时间复杂度: O(N + M)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程