logo

Algorytm Prima dla minimalnego drzewa rozpinającego (MST)

Wprowadzenie do algorytmu Prima:

Omówiliśmy Algorytm Kruskala dla minimalnego drzewa rozpinającego . Podobnie jak algorytm Kruskala, algorytm Prima również jest Chciwy algorytm . Algorytm ten zawsze zaczyna się od pojedynczego węzła i przechodzi przez kilka sąsiednich węzłów, aby po drodze zbadać wszystkie połączone krawędzie.

Algorytm zaczyna się od pustego drzewa opinającego. Chodzi o to, aby zachować dwa zestawy wierzchołków. Pierwszy zestaw zawiera wierzchołki już uwzględnione w MST, a drugi zestaw zawiera wierzchołki jeszcze nieuwzględnione. Na każdym kroku bierze pod uwagę wszystkie krawędzie łączące dwa zbiory i wybiera z tych krawędzi krawędź o minimalnym ciężarze. Po wskazaniu krawędzi przesuwa drugi punkt końcowy krawędzi do zbioru zawierającego MST.



Nazywa się grupę krawędzi łączących dwa zbiory wierzchołków w grafie cięty w teorii grafów . Zatem na każdym kroku algorytmu Prima znajdź cięcie, wybierz krawędź o minimalnej wadze z cięcia i uwzględnij ten wierzchołek w zestawie MST (zbiór, który zawiera już uwzględnione wierzchołki).

Jak działa algorytm Prima?

Działanie algorytmu Prima można opisać, wykonując następujące kroki:

Krok 1: Określ dowolny wierzchołek jako wierzchołek początkowy MST.
Krok 2: Wykonuj kroki od 3 do 5, aż pojawią się wierzchołki, które nie są uwzględnione w MST (tzw. wierzchołek prążkowy).
Krok 3: Znajdź krawędzie łączące dowolny wierzchołek drzewa z wierzchołkami prążkowymi.
Krok 4: Znajdź minimum wśród tych krawędzi.
Krok 5: Dodaj wybraną krawędź do MST, jeśli nie tworzy ona żadnego cyklu.
Krok 6: Wróć MST i wyjdź



Notatka: Aby wyznaczyć cykl, możemy podzielić wierzchołki na dwa zbiory [jeden zestaw zawiera wierzchołki zawarte w MST, a drugi zawiera wierzchołki prążkowe.]

Zalecana praktyka Minimalne drzewo opinające Wypróbuj!

Ilustracja algorytmu Prima:

Rozważmy poniższy wykres jako przykład, dla którego musimy znaleźć minimalne drzewo rozpinające (MST).

Przykład wykresu

Przykład wykresu



Krok 1: Najpierw wybieramy dowolny wierzchołek, który działa jako wierzchołek początkowy minimalnego drzewa rozpinającego. Tutaj wybraliśmy wierzchołek 0 jako wierzchołek początkowy.

Jako wierzchołek początkowy wybrano 0

Jako wierzchołek początkowy wybrano 0

Krok 2: Wszystkie krawędzie łączące niekompletny MST i inne wierzchołki to krawędzie {0, 1} i {0, 7}. Pomiędzy nimi krawędź o minimalnej wadze wynosi {0, 1}. Uwzględnij zatem krawędź i wierzchołek 1 w MST.

1 zostaje dodany do MST

1 zostaje dodany do MST

Podciąg Java zawiera

Krok 3: Krawędzie łączące niekompletny MST z innymi wierzchołkami to {0, 7}, {1, 7} i {1, 2}. Wśród tych krawędzi minimalna waga wynosi 8, czyli krawędzi {0, 7} i {1, 2}. Uwzględnijmy tutaj krawędź {0, 7} i wierzchołek 7 w MST. [Mogliśmy uwzględnić także krawędź {1, 2} i wierzchołek 2 w MST].

7 dodano w MST

7 dodano w MST

Krok 4: Krawędzie łączące niekompletny MST z wierzchołkami prążkowymi to {1, 2}, {7, 6} i {7, 8}. Dodaj krawędź {7, 6} i wierzchołek 6 w MST, ponieważ ma najmniejszą wagę (tj. 1).

6 dodano w MST

6 dodano w MST

Krok 5: Krawędzie łączące to teraz {7, 8}, {1, 2}, {6, 8} i {6, 5}. Uwzględnij krawędź {6, 5} i wierzchołek 5 w MST, ponieważ krawędź ma spośród nich minimalną wagę (tj. 2).

Uwzględnij wierzchołek 5 w MST

Uwzględnij wierzchołek 5 w MST

Krok 6: Spośród obecnych krawędzi łączących krawędź {5, 2} ma minimalną wagę. Uwzględnij więc tę krawędź i wierzchołek 2 w MST.

Uwzględnij wierzchołek 2 w MST

Uwzględnij wierzchołek 2 w MST

Krok 7: Krawędzie łączące między niekompletnym MST a pozostałymi krawędziami to {2, 8}, {2, 3}, {5, 3} i {5, 4}. Krawędź o minimalnej wadze to krawędź {2, 8}, która ma wagę 2. Uwzględnij więc tę krawędź i wierzchołek 8 w MST.

Dodaj wierzchołek 8 w MST

Dodaj wierzchołek 8 w MST

Krok 8: Zobacz tutaj, że krawędzie {7, 8} i {2, 3} mają tę samą wagę, która jest minimalna. Ale 7 jest już częścią MST. Rozważymy więc krawędź {2, 3} i uwzględnimy tę krawędź i wierzchołek 3 w MST.

Uwzględnij wierzchołek 3 w MST

Uwzględnij wierzchołek 3 w MST

Krok 9: Do uwzględnienia pozostaje tylko wierzchołek 4. Minimalna ważona krawędź od niekompletnego MST do 4 wynosi {3, 4}.

Uwzględnij wierzchołek 4 w MST

Uwzględnij wierzchołek 4 w MST

Ostateczna struktura MST jest następująca, a waga krawędzi MST wynosi (4 + 8 + 1 + 2 + 4 + 2 + 7 + 9) = 37 .

Struktura MST utworzona przy użyciu powyższej metody

Struktura MST utworzona przy użyciu powyższej metody

Notatka: Gdybyśmy w trzecim kroku wybrali krawędź {1, 2}, wówczas MST wyglądałby następująco.

Struktura alternatywnego MST, jeśli w MST wybraliśmy krawędź {1, 2}

Struktura alternatywnego MST, jeśli w MST wybraliśmy krawędź {1, 2}

Jak wdrożyć algorytm Prima?

Postępuj zgodnie z podanymi krokami, aby skorzystać z Algorytm Prima wspomniane powyżej w celu znalezienia MST wykresu:

  • Utwórz zestaw mstSet który śledzi wierzchołki już uwzględnione w MST.
  • Przypisz wartość klucza do wszystkich wierzchołków wykresu wejściowego. Zainicjuj wszystkie wartości kluczy jako INFINITE. Przypisz wartość klucza jako 0 dla pierwszego wierzchołka, tak aby był on wybierany jako pierwszy.
  • Chwila mstSet nie obejmuje wszystkich wierzchołków
    • Wybierz wierzchołek W tego tam nie ma mstSet i ma minimalną wartość klucza.
    • Włączać W w mstSet .
    • Zaktualizuj wartość klucza wszystkich sąsiadujących wierzchołków W . Aby zaktualizować wartości kluczy, wykonaj iterację przez wszystkie sąsiadujące wierzchołki.
      • Dla każdego sąsiedniego wierzchołka W , jeśli waga krawędzi u-w jest mniejsza niż poprzednia wartość klucza W , zaktualizuj wartość klucza jako wagę u-w .

Pomysł użycia kluczowych wartości polega na wybraniu minimalnej krawędzi wagi z cięcie . Wartości kluczy są używane tylko dla wierzchołków, które nie są jeszcze uwzględnione w MST, wartość klucza dla tych wierzchołków wskazuje minimalne wagi krawędzi łączące je ze zbiorem wierzchołków zawartych w MST.

Poniżej implementacja podejścia:

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 if (mstSet[v] == false && key[v] 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 Weight '; for (int i = 1; i cout << 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 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; // First node is always root of MST parent[0] = -1; // The MST will have V vertices for (int count = 0; 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 // 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] parent[v] = u, key[v] = graph[u][v]; } // Print the constructed MST printMST(parent, graph); } // Driver's code int main() { 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; } // This code is contributed by rathbhupendra>

>

>

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 if (mstSet[v] == false && key[v] 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 Weight '); for (int i = 1; i printf('%d - %d %d ', 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 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; // First node is always root of MST parent[0] = -1; // The MST will have V vertices for (int count = 0; 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 // 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] parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph); } // Driver's code int main() { 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; }>

>

>

Jawa




// A Java program for Prim's Minimum Spanning Tree (MST)> // algorithm. The program is for adjacency matrix> // representation of the graph> import> java.io.*;> import> java.lang.*;> import> java.util.*;> 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 if (mstSet[v] == false && key[v] 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 Weight'); for (int i = 1; i System.out.println(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[][]) { // 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 key[i] = Integer.MAX_VALUE; 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; // First node is always root of MST parent[0] = -1; // The MST will have V vertices for (int count = 0; count 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 // 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] parent[v] = u; key[v] = graph[u][v]; } } // Print the constructed MST printMST(parent, graph); } public static void main(String[] args) { 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>

>

>

bieżąca data w Javie

Python3




# A Python3 program for> # Prim's Minimum Spanning Tree (MST) algorithm.> # The program is for adjacency matrix> # representation of the graph> # Library for INT_MAX> import> sys> 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 Weight'>)> >for> i>in> range>(>1>,>self>.V):> >print>(parent[i],>'-'>, i,>' '>,>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.maxsize> >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.maxsize]>*> 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 shortest 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)> # Driver's code> if> __name__>=>=> '__main__'>:> >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 if (mstSet[v] == false && key[v] 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 Weight'); for (int i = 1; i Console.WriteLine(parent[i] + ' - ' + i + ' ' + 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 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 // 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 // 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] parent[v] = u; key[v] = graph[u, v]; } } // Print the constructed MST printMST(parent, graph); } // Driver's Code public static void Main() { 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




> // Number of vertices in the graph> let V = 5;> // A utility function to find the vertex with> // minimum key value, from the set of vertices> // not yet included in MST> function> minKey(key, mstSet)> {> >// Initialize min value> >let min = Number.MAX_VALUE, min_index;> >for> (let v = 0; v if (mstSet[v] == false && key[v] min = key[v], min_index = v; return min_index; } // A utility function to print the // constructed MST stored in parent[] function printMST(parent, graph) { document.write('Edge Weight' + ' '); for (let i = 1; i document.write(parent[i] + ' - ' + i + ' ' + graph[i][parent[i]] + ' '); } // Function to construct and print MST for // a graph represented using adjacency // matrix representation function primMST(graph) { // Array to store constructed MST let parent = []; // Key values used to pick minimum weight edge in cut let key = []; // To represent set of vertices included in MST let mstSet = []; // Initialize all keys as INFINITE for (let i = 0; i key[i] = Number.MAX_VALUE, 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 (let count = 0; count { // Pick the minimum key vertex from the // set of vertices not yet included in MST let 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 (let v = 0; 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] parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph); } // Driver code let 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 ] ]; // Print the solution primMST(graph); // This code is contributed by Dharanendra L V.>

>

>

Wyjście

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

Analiza złożoności algorytmu Prima:

Złożoność czasowa: O(V2), Jeśli wejście wykres jest reprezentowany za pomocą listy sąsiedztwa , wówczas złożoność czasową algorytmu Prima można zredukować do O(E * logV) za pomocą sterty binarnej. W tej implementacji zawsze rozważamy rozpoczęcie drzewa rozpinającego od korzenia grafu
Przestrzeń pomocnicza: O(V)

Inne implementacje algorytmu Prima:

Poniżej podano kilka innych implementacji algorytmu Prima

  • Algorytm Prima do reprezentacji macierzy sąsiedztwa – W tym artykule omówiliśmy sposób implementacji algorytmu Prima, jeśli graf jest reprezentowany przez macierz sąsiedztwa.
  • Algorytm Prima do reprezentacji listy sąsiedztwa – W tym artykule opisano implementację algorytmu Prima dla grafów reprezentowanych przez listę sąsiedztwa.
  • Algorytm Prima wykorzystujący kolejkę priorytetową: W tym artykule omówiliśmy efektywne czasowo podejście do implementacji algorytmu Prim.

ZOPTYMALIZOWANE PODEJŚCIE ALGORYTMU PRIM:

Intuicja

  1. Przekształcamy macierz sąsiedztwa w listę sąsiedztwa za pomocą Lista tablic .
  2. Następnie tworzymy klasę Pair do przechowywania wierzchołka i jego wagi.
  3. Sortujemy listę według najniższej wagi.
  4. Tworzymy kolejkę priorytetową i wpychamy do kolejki pierwszy wierzchołek wraz z jego wagą
  5. Następnie po prostu przechodzimy przez jego krawędzie i przechowujemy najmniejszą wagę w zmiennej o nazwie lata.
  6. W końcu po wszystkich wierzchołkach zwracamy ans.

Realizacja

C++




#include> using> namespace> std;> typedef> pair<>int>,>int>>pi;> // Function to find sum of weights of edges of the Minimum Spanning Tree.> int> spanningTree(>int> V,>int> E,>int> edges[][3])> {> >// Create an adjacency list representation of the graph> >vectorint>> przym[V]; // Wypełnij listę sąsiedztwa krawędziami i ich wagami dla (int i = 0; i int u = krawędzie[i][0]; int v = krawędzie[i][1]; int wt = krawędzie[i][2 ]; adj[u].push_back({v, wt}); adj[v].push_back({u, wt}); } // Utwórz kolejkę priorytetową do przechowywania krawędzi z ich wagami priorytet_kolejka pq; odwiedzana tablica do śledzenia wektora odwiedzanych wierzchołków odwiedził(V, fałsz); // Zmienna przechowująca wynik (suma wag krawędzi) int res = 0; // Zacznij od wierzchołka 0 pq.push({0, 0}); // Wykonaj algorytm Prima, aby znaleźć minimalne drzewo rozpinające while(!pq.empty()){ auto p = pq.top(); pq.pop(); int wt = p.pierwszy; // Waga krawędzi int u = p.sekunda; // Wierzchołek połączony z krawędzią if(visited[u] == true){ kontynuuj; // Pomiń, jeśli wierzchołek był już odwiedzony } res += wt; // Dodaj wagę krawędzi do odwiedzonego wyniku[u] = true; // Oznacz wierzchołek jako odwiedzony // Przeglądaj sąsiednie wierzchołki for(auto v : adj[u]){ // v[0] reprezentuje wierzchołek, a v[1] reprezentuje wagę krawędzi if(visited[v[0] ] == fałsz){ pq.push({v[1], v[0]}); // Dodaj sąsiednią krawędź do kolejki priorytetowej } } } return res; // Zwraca sumę wag krawędzi minimalnego drzewa rozpinającego } int main() { int graph[][3] = {{0, 1, 5}, {1, 2, 3}, {0, 2, 1 }}; // Wywołanie funkcji cout<< spanningTree(3, 3, graph) << endl; return 0; }>

>

>

Jawa

shilpa shetty




// A Java program for Prim's Minimum Spanning Tree (MST)> // algorithm. The program is for adjacency list> // representation of the graph> import> java.io.*;> import> java.util.*;> // Class to form pair> class> Pair>implements> Comparable> {> >int> v;> >int> wt;> >Pair(>int> v,>int> wt)> >{> >this>.v=v;> >this>.wt=wt;> >}> >public> int> compareTo(Pair that)> >{> >return> this>.wt-that.wt;> >}> }> class> GFG {> // Function of spanning tree> static> int> spanningTree(>int> V,>int> E,>int> edges[][])> >{> >ArrayList adj=>new> ArrayList();> >for>(>int> i=>0>;i { adj.add(new ArrayList()); } for(int i=0;i { int u=edges[i][0]; int v=edges[i][1]; int wt=edges[i][2]; adj.get(u).add(new Pair(v,wt)); adj.get(v).add(new Pair(u,wt)); } PriorityQueue pq = new PriorityQueue(); pq.add(new Pair(0,0)); int[] vis=new int[V]; int s=0; while(!pq.isEmpty()) { Pair node=pq.poll(); int v=node.v; int wt=node.wt; if(vis[v]==1) continue; s+=wt; vis[v]=1; for(Pair it:adj.get(v)) { if(vis[it.v]==0) { pq.add(new Pair(it.v,it.wt)); } } } return s; } // Driver code public static void main (String[] args) { int graph[][] = new int[][] {{0,1,5}, {1,2,3}, {0,2,1}}; // Function call System.out.println(spanningTree(3,3,graph)); } }>

>

>

Python3




import> heapq> def> tree(V, E, edges):> ># Create an adjacency list representation of the graph> >adj>=> [[]>for> _>in> range>(V)]> ># Fill the adjacency list with edges and their weights> >for> i>in> range>(E):> >u, v, wt>=> edges[i]> >adj[u].append((v, wt))> >adj[v].append((u, wt))> ># Create a priority queue to store edges with their weights> >pq>=> []> ># Create a visited array to keep track of visited vertices> >visited>=> [>False>]>*> V> ># Variable to store the result (sum of edge weights)> >res>=> 0> ># Start with vertex 0> >heapq.heappush(pq, (>0>,>0>))> ># Perform Prim's algorithm to find the Minimum Spanning Tree> >while> pq:> >wt, u>=> heapq.heappop(pq)> >if> visited[u]:> >continue> ># Skip if the vertex is already visited> >res>+>=> wt> ># Add the edge weight to the result> >visited[u]>=> True> ># Mark the vertex as visited> ># Explore the adjacent vertices> >for> v, weight>in> adj[u]:> >if> not> visited[v]:> >heapq.heappush(pq, (weight, v))> ># Add the adjacent edge to the priority queue> >return> res> ># Return the sum of edge weights of the Minimum Spanning Tree> if> __name__>=>=> '__main__'>:> >graph>=> [[>0>,>1>,>5>],> >[>1>,>2>,>3>],> >[>0>,>2>,>1>]]> ># Function call> >print>(tree(>3>,>3>, graph))>

>

>

C#




wiek Sary Ali Khan

using> System;> using> System.Collections.Generic;> public> class> MinimumSpanningTree> {> >// Function to find sum of weights of edges of the Minimum Spanning Tree.> >public> static> int> SpanningTree(>int> V,>int> E,>int>[,] edges)> >{> >// Create an adjacency list representation of the graph> >Listint[]>> adj = nowy Listint[]>>(); for (int i = 0; i {przym.Add(nowa lista ()); } // Wypełnij listę sąsiedztwa krawędziami i ich wagami dla (int i = 0; i { int u = krawędzie[i, 0]; int v = krawędzie[i, 1]; int wt = krawędzie[i, 2] ; adj[u].Add(new int[] { v, wt }); adj[v].Add(new int[] {u, wt }); // Utwórz kolejkę priorytetową do przechowywania krawędzi z ich wagami Kolejka priorytetowa<(int, int)>pq = nowa kolejka priorytetów<(int, int)>(); // Utwórz tablicę odwiedzanych, aby śledzić odwiedzane wierzchołki. bool[] odwiedzane = new bool[V]; // Zmienna przechowująca wynik (suma wag krawędzi) int res = 0; // Zacznij od wierzchołka 0 pq.Enqueue((0, 0)); // Wykonaj algorytm Prima, aby znaleźć minimalne drzewo rozpinające while (pq.Count> 0) { var p = pq.Dequeue(); int wt = p.Pozycja1; // Waga krawędzi int u = p.Item2; // Wierzchołek połączony z krawędzią if (visited[u]) { kontynuuj; // Pomiń, jeśli wierzchołek był już odwiedzony } res += wt; // Dodaj wagę krawędzi do odwiedzonego wyniku[u] = true; // Oznacz wierzchołek jako odwiedzony // Zbadaj sąsiednie wierzchołki foreach (var v in adj[u]) { // v[0] reprezentuje wierzchołek, a v[1] reprezentuje wagę krawędzi if (!visited[v[0 ]]) { pq.Kolejka((v[1], v[0])); // Dodaj sąsiednią krawędź do kolejki priorytetowej } } } return res; // Zwraca sumę wag krawędzi minimalnego drzewa opinającego } public static void Main() { int[,] graph = { { 0, 1, 5 }, { 1, 2, 3 }, { 0, 2, 1 } }; // Wywołanie funkcji Console.WriteLine(SpanningTree(3, 3, graph)); } } // Implementacja PriorityQueue dla publicznej klasy C# PriorityQueue gdzie T : IComparable { private List heap = new List(); public int Count => sterta.Count; public void Kolejka (element T) { heap.Add (element); int i = sterta.Count - 1; while (i> 0) { int rodzic = (i - 1) / 2; if (sterta[nadrzędny].CompareTo(sterta[i])<= 0) break; Swap(parent, i); i = parent; } } public T Dequeue() { int lastIndex = heap.Count - 1; T frontItem = heap[0]; heap[0] = heap[lastIndex]; heap.RemoveAt(lastIndex); --lastIndex; int parent = 0; while (true) { int leftChild = parent * 2 + 1; if (leftChild>lastIndex) przerwa; int praweDziecko = leweDziecko + 1; if (rightChild 0) leftChild = praweDziecko; if (sterta[parent].CompareTo(heap[leftChild])<= 0) break; Swap(parent, leftChild); parent = leftChild; } return frontItem; } private void Swap(int i, int j) { T temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } } // This code is contributed by shivamgupta0987654321>

>

>

JavaScript




class PriorityQueue {> >constructor() {> >this>.heap = [];> >}> >enqueue(value) {> >this>.heap.push(value);> >let i =>this>.heap.length - 1;> >while> (i>0) {> >let j = Math.floor((i - 1) / 2);> >if> (>this>.heap[i][0]>=>this>.heap[j][0]) {> >break>;> >}> >[>this>.heap[i],>this>.heap[j]] = [>this>.heap[j],>this>.heap[i]];> >i = j;> >}> >}> >dequeue() {> >if> (>this>.heap.length === 0) {> >throw> new> Error(>'Queue is empty'>);> >}> >let i =>this>.heap.length - 1;> >const result =>this>.heap[0];> >this>.heap[0] =>this>.heap[i];> >this>.heap.pop();> >i--;> >let j = 0;> >while> (>true>) {> >const left = j * 2 + 1;> >if> (left>i) {> >break>;> >}> >const right = left + 1;> >let k = left;> >if> (right <= i &&>this>.heap[right][0] <>this>.heap[left][0]) {> >k = right;> >}> >if> (>this>.heap[j][0] <=>this>.heap[k][0]) {> >break>;> >}> >[>this>.heap[j],>this>.heap[k]] = [>this>.heap[k],>this>.heap[j]];> >j = k;> >}> >return> result;> >}> >get count() {> >return> this>.heap.length;> >}> }> function> spanningTree(V, E, edges) {> >// Create an adjacency list representation of the graph> >const adj =>new> Array(V).fill(>null>).map(() =>[]);> >// Fill the adjacency list with edges and their weights> >for> (let i = 0; i const [u, v, wt] = edges[i]; adj[u].push([v, wt]); adj[v].push([u, wt]); } // Create a priority queue to store edges with their weights const pq = new PriorityQueue(); // Create a visited array to keep track of visited vertices const visited = new Array(V).fill(false); // Variable to store the result (sum of edge weights) let res = 0; // Start with vertex 0 pq.enqueue([0, 0]); // Perform Prim's algorithm to find the Minimum Spanning Tree while (pq.count>0) { const p = pq.dequeue(); stała wt = p[0]; // Waga krawędzi const u = p[1]; // Wierzchołek połączony z krawędzią if (visited[u]) { kontynuuj; // Pomiń, jeśli wierzchołek był już odwiedzony } res += wt; // Dodaj wagę krawędzi do odwiedzonego wyniku[u] = true; // Oznacz wierzchołek jako odwiedzony // Zbadaj sąsiednie wierzchołki for (const v of adj[u]) { // v[0] reprezentuje wierzchołek, a v[1] reprezentuje wagę krawędzi if (!visited[v[0 ]]) { pq.enqueue([v[1], v[0]]); // Dodaj sąsiednią krawędź do kolejki priorytetowej } } } return res; // Zwraca sumę wag krawędzi minimalnego drzewa rozpinającego } // Przykładowy wykres stałych użycia = [[0, 1, 5], [1, 2, 3], [0, 2, 1]]; // Wywołanie funkcji console.log(spanningTree(3, 3, graph));>

>

>

Wyjście

4>

Analiza złożoności algorytmu Prima:

Złożoność czasowa: O(E*log(E)) gdzie E jest liczbą krawędzi
Przestrzeń pomocnicza: O(V^2) gdzie V jest numerem wierzchołka

Algorytm Prima do znajdowania minimalnego drzewa rozpinającego (MST):

Zalety:

  1. Algorytm Prima gwarantuje znalezienie MST na połączonym, ważonym wykresie.
  2. Ma złożoność czasową O (E log V) przy użyciu sterty binarnej lub sterty Fibonacciego, gdzie E to liczba krawędzi, a V to liczba wierzchołków.
  3. Jest to stosunkowo prosty algorytm do zrozumienia i wdrożenia w porównaniu z niektórymi innymi algorytmami MST.

Niedogodności:

  1. Podobnie jak algorytm Kruskala, algorytm Prima może działać wolno na gęstych grafach z wieloma krawędziami, ponieważ wymaga co najmniej jednej iteracji po wszystkich krawędziach.
  2. Algorytm Prim opiera się na kolejce priorytetowej, która może zająć dodatkową pamięć i spowolnić algorytm w przypadku bardzo dużych wykresów.
  3. Wybór węzła początkowego może mieć wpływ na wynik MST, co może nie być pożądane w niektórych zastosowaniach.