📌  相关文章
📜  在边权重为 0 或 1 的完整图中查找 MST 的权重

📅  最后修改于: 2021-09-04 13:08:25             🧑  作者: Mango

给定一个N个顶点的无向加权完全图。正好有M 条边的权重为 1,其余所有可能的边的权重为 0。数组arr[][]给出权重为 1 的边集。任务是计算该图的最小生成树的总权重.
例子:

方法:
对于要成为连通分量的N 个节点的给定图,我们恰好需要N-11 权重边的边。以下是步骤:

  1. 将给定的图存储在地图中,用于权重为 1 的所有边。
  2. 使用 set 来存储不包含在任何0-weight Connected Components 中的顶点。
  3. 对于当前存储在集合中的每个顶点,执行 DFS 遍历并将组件的计数增加 1,并从集合中删除所有在 DFS 遍历期间访问过的顶点。
  4. 在 DFS 遍历期间,将向量中的0 权重顶点和另一组中的 1 权重顶点包括在内。对向量中包含的所有顶点运行 DFS 遍历。
  5. 然后,最小生成树的总权重被赋予组件数 – 1。

下面是上述方法的实现:

C++
// C++ Program to find weight of
// minimum spanning tree in a
// complete graph where edges
// have weight either 0 or 1
#include 
using namespace std;
 
// To store the edges of the given
// graph
map g[200005];
set s, ns;
 
// A utility function to perform
// DFS Traversal
void dfs(int x)
{
    vector v;
    v.clear();
    ns.clear();
 
    // Check those vertices which
    // are stored in the set
    for (int it : s) {
        // Vertices are included if
        // the weight of edge is 0
        if (!g[x][it]) {
            v.push_back(it);
        }
        else {
            ns.insert(it);
        }
    }
    s = ns;
    for (int i : v) {
        dfs(i);
    }
}
 
// A utility function to find the
// weight of Minimum Spanning Tree
void weightOfMST(int N)
{
    // To count the connected
    // components
    int cnt = 0;
 
    // Inserting the initial vertices
    // in the set
    for (int i = 1; i <= N; ++i) {
        s.insert(i);
    }
 
    // Traversing vertices stored in
    // the set and Run DFS Traversal
    // for each vertices
    for (; s.size();) {
 
        // Incrementing the zero
        // weight connected components
        ++cnt;
 
        int t = *s.begin();
        s.erase(t);
 
        // DFS Traversal for every
        // vertex remove
        dfs(t);
    }
 
    cout << cnt - 1;
}
 
// Driver's Code
int main()
{
    int N = 6, M = 11;
    int edges[][] = { { 1, 3 }, { 1, 4 },
                      { 1, 5 }, { 1, 6 },
                      { 2, 3 }, { 2, 4 },
                      { 2, 5 }, { 2, 6 },
                      { 3, 4 }, { 3, 5 },
                      { 3, 6 } };
 
    // Insert edges
    for (int i = 0; i < M; ++i) {
        int u = edges[i][0];
        int v = edges[i][1];
        g[u][v] = 1;
        g[v][u] = 1;
    }
 
    // Function call find the weight
    // of Minimum Spanning Tree
    weightOfMST(N);
    return 0;
}


Java
// Java Program to find weight of
// minimum spanning tree in a
// complete graph where edges
// have weight either 0 or 1
import java.util.*;
 
class GFG{
 
// To store the edges
// of the given graph
static HashMap[] g =
               new HashMap[200005];
static HashSet s =
               new HashSet<>();
static HashSet ns =
               new HashSet<>();
 
// A utility function to
// perform DFS Traversal
static void dfs(int x)
{
  Vector v = new Vector<>();
  v.clear();
  ns.clear();
 
  // Check those vertices which
  // are stored in the set
  for (int it : s)
  {
    // Vertices are included if
    // the weight of edge is 0
    if (g[x].get(it) != null)
    {
      v.add(it);
    }
    else
    {
      ns.add(it);
    }
  }
   
  s = ns;
   
  for (int i : v)
  {
    dfs(i);
  }
}
 
// A utility function to find the
// weight of Minimum Spanning Tree
static void weightOfMST(int N)
{
  // To count the connected
  // components
  int cnt = 0;
 
  // Inserting the initial vertices
  // in the set
  for (int i = 1; i <= N; ++i)
  {
    s.add(i);
  }
 
  Vector qt = new Vector<>();
   
  for (int t : s)
    qt.add(t);
   
  // Traversing vertices stored in
  // the set and Run DFS Traversal
  // for each vertices
  while (!qt.isEmpty())
  {
    // Incrementing the zero
    // weight connected components
    ++cnt;
    int t = qt.get(0);
    qt.remove(0);
     
    // DFS Traversal for every
    // vertex remove
    dfs(t);
  }
 
  System.out.print(cnt - 4);
}
 
// Driver's Code
public static void main(String[] args)
{
  int N = 6, M = 11;
  int edges[][] = {{1, 3}, {1, 4},
                   {1, 5}, {1, 6},
                   {2, 3}, {2, 4},
                   {2, 5}, {2, 6},
                   {3, 4}, {3, 5},
                   {3, 6}};
 
  for (int i = 0; i < g.length; i++)
    g[i] = new HashMap();
  // Insert edges
  for (int i = 0; i < M; ++i)
  {
    int u = edges[i][0];
    int v = edges[i][1];
    g[u].put(v, 1);
    g[v].put(u, 1);
 
  }
 
  // Function call find the weight
  // of Minimum Spanning Tree
  weightOfMST(N);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 Program to find weight of
# minimum spanning tree in a
# complete graph where edges
# have weight either 0 or 1
 
# To store the edges of the given
# graph
 
g = [dict() for i in range(200005)]
s = set()
ns = set()
  
# A utility function to perform
# DFS Traversal
def dfs(x):
    global s, g, ns
    v = []
    v.clear();
    ns.clear();
  
    # Check those vertices which
    # are stored in the set
    for it in s:
     
        # Vertices are included if
        # the weight of edge is 0
        if (x in g and not g[x][it]):
            v.append(it);
         
        else:
            ns.add(it);
 
    s = ns;
     
    for i in v:
     
        dfs(i);
 
# A utility function to find the
# weight of Minimum Spanning Tree
def weightOfMST( N):
 
    # To count the connected
    # components
    cnt = 0;
  
    # Inserting the initial vertices
    # in the set
    for i in range(1,N + 1):
     
        s.add(i);
     
    # Traversing vertices stored in
    # the set and Run DFS Traversal
    # for each vertices
    while(len(s) != 0):
  
        # Incrementing the zero
        # weight connected components
        cnt += 1
  
        t = list(s)[0]
        s.discard(t);
  
        # DFS Traversal for every
        # vertex remove
        dfs(t);
     
    print(cnt)
   
# Driver's Code
if __name__=='__main__':
     
    N = 6
    M = 11;
    edges = [ [ 1, 3 ], [ 1, 4 ],
                      [ 1, 5 ], [ 1, 6 ],
                      [ 2, 3 ], [ 2, 4 ],
                      [ 2, 5 ], [ 2, 6 ],
                      [ 3, 4 ], [ 3, 5 ],
                      [ 3, 6 ] ];
  
    # Insert edges
    for i in range(M):
     
        u = edges[i][0];
        v = edges[i][1];
        g[u][v] = 1;
        g[v][u] = 1;
      
    # Function call find the weight
    # of Minimum Spanning Tree
    weightOfMST(N);
 
# This code is contributed by pratham76


C#
// C# Program to find weight of
// minimum spanning tree in a
// complete graph where edges
// have weight either 0 or 1
using System;
using System.Collections;
using System.Collections.Generic;
 class GFG{
  
// To store the edges
// of the given graph
static Dictionary [] g =  new Dictionary[200005];
static HashSet s = new HashSet();
static HashSet ns = new HashSet();
  
// A utility function to
// perform DFS Traversal
static void dfs(int x)
{
  ArrayList v = new ArrayList();
   
  ns.Clear();
  
  // Check those vertices which
  // are stored in the set
  foreach (int it in s)
  {
    // Vertices are included if
    // the weight of edge is 0
    if (g[x].ContainsKey(it))
    {
      v.Add(it);
    }
    else
    {
      ns.Add(it);
    }
  }
  s = ns;  
  foreach(int i in v)
  {
    dfs(i);
  }
}
  
// A utility function to find the
// weight of Minimum Spanning Tree
static void weightOfMST(int N)
{
  // To count the connected
  // components
  int cnt = 0;
  
  // Inserting the initial vertices
  // in the set
  for (int i = 1; i <= N; ++i)
  {
    s.Add(i);
  }
  
  ArrayList qt = new ArrayList();
    
  foreach(int t in s)
    qt.Add(t);
    
  // Traversing vertices stored in
  // the set and Run DFS Traversal
  // for each vertices
  while (qt.Count != 0)
  {
    // Incrementing the zero
    // weight connected components
    ++cnt;
    int t = (int)qt[0];
    qt.RemoveAt(0);
      
    // DFS Traversal for every
    // vertex remove
    dfs(t);
  }
  
  Console.Write(cnt - 4);
}
  
// Driver's Code
public static void Main(string[] args)
{
  int N = 6, M = 11;
  int [,]edges = {{1, 3}, {1, 4},
                   {1, 5}, {1, 6},
                   {2, 3}, {2, 4},
                   {2, 5}, {2, 6},
                   {3, 4}, {3, 5},
                   {3, 6}};
  
  for (int i = 0; i < 11; i++)
    g[i] = new Dictionary();
     
  // Insert edges
  for (int i = 0; i < M; ++i)
  {
    int u = edges[i, 0];
    int v = edges[i, 1];
    g[u][v] = 1;
    g[v][u] = 1;
  }
  
  // Function call find the weight
  // of Minimum Spanning Tree
  weightOfMST(N);
}
}
 
// This code is contributed by rutvik_56


输出:
2

时间复杂度: O(N*log N + M),其中 N 是顶点数,M 是边数。

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live