📜  Prim 的最小生成树 (MST) |贪婪算法5

📅  最后修改于: 2021-10-27 06:17:55             🧑  作者: Mango

我们已经讨论了 Kruskal 的最小生成树算法。和 Kruskal 算法一样,Prim 算法也是一种贪心算法。它从一棵空的生成树开始。这个想法是维护两组顶点。第一组包含已包含在 MST 中的顶点,另一组包含尚未包含的顶点。在每一步,它都会考虑连接这两个集合的所有边,并从这些边中挑选出权重最小的边。拾取边后,它将边的另一个端点移动到包含 MST 的集合中。
连接图中两组顶点的一组边在图论中称为割。因此,在 Prim 算法的每一步,我们都会找到一个切割(两个集合,一个包含已经包含在 MST 中的顶点,另一个包含其余的顶点),从切割中选择权重最小的边并将这个顶点包含到 MST 集合中(包含已包含顶点的集合)。
Prim 的算法是如何工作的? Prim 算法背后的思想很简单,生成树意味着必须连接所有顶点。因此必须连接两个不相交的顶点子集(上面讨论过)以形成生成树。并且它们必须与最小权重边相连以使其成为最小生成树。
算法
1)创建一个集合mstSet来跟踪已经包含在 MST 中的顶点。
2)为输入图中的所有顶点分配一个键值。将所有键值初始化为 INFINITE。将第一个顶点的键值指定为 0,以便它首先被拾取。
3)虽然 mstSet 不包括所有顶点
…… a)选择mstSet 中不存在的顶点u并且具有最小键值。
…… b) 将u包含到 mstSet。
…… c)更新u的所有相邻顶点的键值。要更新键值,请遍历所有相邻顶点。对于每个相邻的顶点v ,如果边uv 的权重小于v的前一个键值,则将键值更新为uv 的权重
使用键值的想法是从 cut 中选择权重最小的边。键值仅用于尚未包含在 MST 中的顶点,这些顶点的键值表示将它们连接到包含在 MST 中的顶点集的最小权重边。

让我们通过下面的例子来理解:

集合mstSet最初是空的,分配给顶点的键是 {0, INF, INF, INF, INF, INF, INF, INF},其中 INF 表示无限。现在选择具有最小键值的顶点。顶点 0 被拾取,将其包含在mstSet 中。因此mstSet变为 {0}。包含到mstSet 后,更新相邻顶点的键值。 0 的相邻顶点是 1 和 7。1 和 7 的键值更新为 4 和 8。下面的子图显示了顶点及其键值,仅显示了具有有限键值的顶点。 MST 中包含的顶点以绿色显示。

选择具有最小键值且尚未包含在 MST 中(不在 mstSET 中)的顶点。顶点 1 被拾取并添加到 mstSet。所以 mstSet 现在变成了 {0, 1}。更新1的相邻顶点的键值,顶点2的键值变为8。

选择具有最小键值且尚未包含在 MST 中(不在 mstSET 中)的顶点。我们可以选择顶点 7 或顶点 2,让顶点 7 被拾取。所以 mstSet 现在变成了 {0, 1, 7}。更新 7 的相邻顶点的键值。顶点 6 和 8 的键值变为有限(分别为 1 和 7)。

选择具有最小键值且尚未包含在 MST 中(不在 mstSET 中)的顶点。顶点 6 被选取。所以 mstSet 现在变成了 {0, 1, 7, 6}。更新6的相邻顶点的键值。更新顶点5和8的键值。

我们重复上述步骤,直到mstSet包含给定图的所有顶点。最后,我们得到下图。

如何实现上述算法?
我们使用布尔数组 mstSet[] 来表示 MST 中包含的顶点集。如果值 mstSet[v] 为真,则顶点 v 包含在 MST 中,否则不包含。数组 key[] 用于存储所有顶点的键值。另一个数组 parent[] 用于在 MST 中存储父节点的索引。父数组是用于显示构造的 MST 的输出数组。

C++
// A C++ program for Prim's Minimum
// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph
#include 
using namespace std;
 
// Number of vertices in the graph
#define V 5
 
// A utility function to find the vertex with
// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
    // Initialize min value
    int min = INT_MAX, min_index;
 
    for (int v = 0; v < V; v++)
        if (mstSet[v] == false && key[v] < min)
            min = key[v], min_index = v;
 
    return min_index;
}
 
// A utility function to print the
// constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V])
{
    cout<<"Edge \tWeight\n";
    for (int i = 1; i < V; i++)
        cout<


C
// A C program for Prim's Minimum
// Spanning Tree (MST) algorithm. The program is
// for adjacency matrix representation of the graph
#include 
#include 
#include 
// Number of vertices in the graph
#define V 5
 
// A utility function to find the vertex with
// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
    // Initialize min value
    int min = INT_MAX, min_index;
 
    for (int v = 0; v < V; v++)
        if (mstSet[v] == false && key[v] < min)
            min = key[v], min_index = v;
 
    return min_index;
}
 
// A utility function to print the
// constructed MST stored in parent[]
int printMST(int parent[], int graph[V][V])
{
    printf("Edge \tWeight\n");
    for (int i = 1; i < V; i++)
        printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
 
// Function to construct and print MST for
// a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
    // Array to store constructed MST
    int parent[V];
    // Key values used to pick minimum weight edge in cut
    int key[V];
    // To represent set of vertices included in MST
    bool mstSet[V];
 
    // Initialize all keys as INFINITE
    for (int i = 0; i < V; i++)
        key[i] = INT_MAX, mstSet[i] = false;
 
    // Always include first 1st vertex in MST.
    // Make key 0 so that this vertex is picked as first vertex.
    key[0] = 0;
    parent[0] = -1; // First node is always root of MST
 
    // The MST will have V vertices
    for (int count = 0; count < V - 1; count++) {
        // Pick the minimum key vertex from the
        // set of vertices not yet included in MST
        int u = minKey(key, mstSet);
 
        // Add the picked vertex to the MST Set
        mstSet[u] = true;
 
        // Update key value and parent index of
        // the adjacent vertices of the picked vertex.
        // Consider only those vertices which are not
        // yet included in MST
        for (int v = 0; v < V; v++)
 
            // graph[u][v] is non zero only for adjacent vertices of m
            // mstSet[v] is false for vertices not yet included in MST
            // Update the key only if graph[u][v] is smaller than key[v]
            if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
                parent[v] = u, key[v] = graph[u][v];
    }
 
    // print the constructed MST
    printMST(parent, graph);
}
 
// driver program to test above function
int main()
{
    /* Let us create the following graph
        2 3
    (0)--(1)--(2)
    | / \ |
    6| 8/ \5 |7
    | /     \ |
    (3)-------(4)
            9         */
    int graph[V][V] = { { 0, 2, 0, 6, 0 },
                        { 2, 0, 3, 8, 5 },
                        { 0, 3, 0, 0, 7 },
                        { 6, 8, 0, 0, 9 },
                        { 0, 5, 7, 9, 0 } };
 
    // Print the solution
    primMST(graph);
 
    return 0;
}


Java
// A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
// The program is for adjacency matrix representation of the graph
 
import java.util.*;
import java.lang.*;
import java.io.*;
 
class MST {
    // Number of vertices in the graph
    private static final int V = 5;
 
    // A utility function to find the vertex with minimum key
    // value, from the set of vertices not yet included in MST
    int minKey(int key[], Boolean mstSet[])
    {
        // Initialize min value
        int min = Integer.MAX_VALUE, min_index = -1;
 
        for (int v = 0; v < V; v++)
            if (mstSet[v] == false && key[v] < min) {
                min = key[v];
                min_index = v;
            }
 
        return min_index;
    }
 
    // A utility function to print the constructed MST stored in
    // parent[]
    void printMST(int parent[], int graph[][])
    {
        System.out.println("Edge \tWeight");
        for (int i = 1; i < V; i++)
            System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
    }
 
    // Function to construct and print MST for a graph represented
    // using adjacency matrix representation
    void primMST(int graph[][])
    {
        // Array to store constructed MST
        int parent[] = new int[V];
 
        // Key values used to pick minimum weight edge in cut
        int key[] = new int[V];
 
        // To represent set of vertices included in MST
        Boolean mstSet[] = new Boolean[V];
 
        // Initialize all keys as INFINITE
        for (int i = 0; i < V; i++) {
            key[i] = Integer.MAX_VALUE;
            mstSet[i] = false;
        }
 
        // Always include first 1st vertex in MST.
        key[0] = 0; // Make key 0 so that this vertex is
        // picked as first vertex
        parent[0] = -1; // First node is always root of MST
 
        // The MST will have V vertices
        for (int count = 0; count < V - 1; count++) {
            // Pick thd minimum key vertex from the set of vertices
            // not yet included in MST
            int u = minKey(key, mstSet);
 
            // Add the picked vertex to the MST Set
            mstSet[u] = true;
 
            // Update key value and parent index of the adjacent
            // vertices of the picked vertex. Consider only those
            // vertices which are not yet included in MST
            for (int v = 0; v < V; v++)
 
                // graph[u][v] is non zero only for adjacent vertices of m
                // mstSet[v] is false for vertices not yet included in MST
                // Update the key only if graph[u][v] is smaller than key[v]
                if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
                    parent[v] = u;
                    key[v] = graph[u][v];
                }
        }
 
        // print the constructed MST
        printMST(parent, graph);
    }
 
    public static void main(String[] args)
    {
        /* Let us create the following graph
        2 3
        (0)--(1)--(2)
        | / \ |
        6| 8/ \5 |7
        | /     \ |
        (3)-------(4)
            9         */
        MST t = new MST();
        int graph[][] = new int[][] { { 0, 2, 0, 6, 0 },
                                      { 2, 0, 3, 8, 5 },
                                      { 0, 3, 0, 0, 7 },
                                      { 6, 8, 0, 0, 9 },
                                      { 0, 5, 7, 9, 0 } };
 
        // Print the solution
        t.primMST(graph);
    }
}
// This code is contributed by Aakash Hasija


Python
# A Python program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph
 
import sys # Library for INT_MAX
 
class Graph():
 
    def __init__(self, vertices):
        self.V = vertices
        self.graph = [[0 for column in range(vertices)]
                    for row in range(vertices)]
 
    # A utility function to print the constructed MST stored in parent[]
    def printMST(self, parent):
        print "Edge \tWeight"
        for i in range(1, self.V):
            print parent[i], "-", i, "\t", self.graph[i][ parent[i] ]
 
    # A utility function to find the vertex with
    # minimum distance value, from the set of vertices
    # not yet included in shortest path tree
    def minKey(self, key, mstSet):
 
        # Initialize min value
        min = sys.maxint
 
        for v in range(self.V):
            if key[v] < min and mstSet[v] == False:
                min = key[v]
                min_index = v
 
        return min_index
 
    # Function to construct and print MST for a graph
    # represented using adjacency matrix representation
    def primMST(self):
 
        # Key values used to pick minimum weight edge in cut
        key = [sys.maxint] * self.V
        parent = [None] * self.V # Array to store constructed MST
        # Make key 0 so that this vertex is picked as first vertex
        key[0] = 0
        mstSet = [False] * self.V
 
        parent[0] = -1 # First node is always the root of
 
        for cout in range(self.V):
 
            # Pick the minimum distance vertex from
            # the set of vertices not yet processed.
            # u is always equal to src in first iteration
            u = self.minKey(key, mstSet)
 
            # Put the minimum distance vertex in
            # the shortest path tree
            mstSet[u] = True
 
            # Update dist value of the adjacent vertices
            # of the picked vertex only if the current
            # distance is greater than new distance and
            # the vertex in not in the shotest path tree
            for v in range(self.V):
 
                # graph[u][v] is non zero only for adjacent vertices of m
                # mstSet[v] is false for vertices not yet included in MST
                # Update the key only if graph[u][v] is smaller than key[v]
                if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
                        key[v] = self.graph[u][v]
                        parent[v] = u
 
        self.printMST(parent)
 
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
            [2, 0, 3, 8, 5],
            [0, 3, 0, 0, 7],
            [6, 8, 0, 0, 9],
            [0, 5, 7, 9, 0]]
 
g.primMST();
 
# Contributed by Divyanshu Mehta


C#
// A C# program for Prim's Minimum
// Spanning Tree (MST) algorithm.
// The program is for adjacency
// matrix representation of the graph
using System;
class MST {
 
    // Number of vertices in the graph
    static int V = 5;
 
    // A utility function to find
    // the vertex with minimum key
    // value, from the set of vertices
    // not yet included in MST
    static int minKey(int[] key, bool[] mstSet)
    {
 
        // Initialize min value
        int min = int.MaxValue, min_index = -1;
 
        for (int v = 0; v < V; v++)
            if (mstSet[v] == false && key[v] < min) {
                min = key[v];
                min_index = v;
            }
 
        return min_index;
    }
 
    // A utility function to print
    // the constructed MST stored in
    // parent[]
    static void printMST(int[] parent, int[, ] graph)
    {
        Console.WriteLine("Edge \tWeight");
        for (int i = 1; i < V; i++)
            Console.WriteLine(parent[i] + " - " + i + "\t" + graph[i, parent[i]]);
    }
 
    // Function to construct and
    // print MST for a graph represented
    // using adjacency matrix representation
    static void primMST(int[, ] graph)
    {
 
        // Array to store constructed MST
        int[] parent = new int[V];
 
        // Key values used to pick
        // minimum weight edge in cut
        int[] key = new int[V];
 
        // To represent set of vertices
        // included in MST
        bool[] mstSet = new bool[V];
 
        // Initialize all keys
        // as INFINITE
        for (int i = 0; i < V; i++) {
            key[i] = int.MaxValue;
            mstSet[i] = false;
        }
 
        // Always include first 1st vertex in MST.
        // Make key 0 so that this vertex is
        // picked as first vertex
        // First node is always root of MST
        key[0] = 0;
        parent[0] = -1;
 
        // The MST will have V vertices
        for (int count = 0; count < V - 1; count++) {
 
            // Pick thd minimum key vertex
            // from the set of vertices
            // not yet included in MST
            int u = minKey(key, mstSet);
 
            // Add the picked vertex
            // to the MST Set
            mstSet[u] = true;
 
            // Update key value and parent
            // index of the adjacent vertices
            // of the picked vertex. Consider
            // only those vertices which are
            // not yet included in MST
            for (int v = 0; v < V; v++)
 
                // graph[u][v] is non zero only
                // for adjacent vertices of m
                // mstSet[v] is false for vertices
                // not yet included in MST Update
                // the key only if graph[u][v] is
                // smaller than key[v]
                if (graph[u, v] != 0 && mstSet[v] == false
                    && graph[u, v] < key[v]) {
                    parent[v] = u;
                    key[v] = graph[u, v];
                }
        }
 
        // print the constructed MST
        printMST(parent, graph);
    }
 
    // Driver Code
    public static void Main()
    {
 
        /* Let us create the following graph
        2 3
        (0)--(1)--(2)
        | / \ |
        6| 8/ \5 |7
        | / \ |
        (3)-------(4)
            9 */
 
        int[, ] graph = new int[, ] { { 0, 2, 0, 6, 0 },
                                      { 2, 0, 3, 8, 5 },
                                      { 0, 3, 0, 0, 7 },
                                      { 6, 8, 0, 0, 9 },
                                      { 0, 5, 7, 9, 0 } };
 
        // Print the solution
        primMST(graph);
    }
}
 
// This code is contributed by anuj_67.


Javascript


输出:

Edge   Weight
0 - 1    2
1 - 2    3
0 - 3    6
1 - 4    5

上述程序的时间复杂度为 O(V^2)。如果输入图使用邻接表表示,那么借助二叉堆,Prim 算法的时间复杂度可以降低到 O(E log V)。有关更多详细信息,请参阅 Prim 的 MST for Adjacency List Representation。

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