logo

Primov algoritmus pre minimálny Spanning Tree (MST)

Úvod do Primovho algoritmu:

Diskutovali sme Kruskalov algoritmus pre minimálnu kostru . Podobne ako Kruskalov algoritmus, aj Primov algoritmus je a Chamtivý algoritmus . Tento algoritmus vždy začína jedným uzlom a prechádza niekoľkými susednými uzlami, aby preskúmal všetky spojené hrany pozdĺž cesty.

Algoritmus začína s prázdnym kostrou. Cieľom je zachovať dve sady vrcholov. Prvá množina obsahuje vrcholy už zahrnuté v MST a druhá množina obsahuje vrcholy, ktoré ešte nie sú zahrnuté. Pri každom kroku berie do úvahy všetky hrany, ktoré spájajú tieto dve sady, a z týchto hrán vyberie hranu s minimálnou hmotnosťou. Po vybratí hrany presunie druhý koncový bod hrany do množiny obsahujúcej MST.



Skupina hrán, ktorá spája dve sady vrcholov v grafe, sa nazýva rez v teórii grafov . Takže v každom kroku Primovho algoritmu nájdite rez, vyberte hranu s minimálnou hmotnosťou z rezu a zahrňte tento vrchol do sady MST (množina, ktorá obsahuje už zahrnuté vrcholy).

Ako funguje Primov algoritmus?

Fungovanie Primovho algoritmu možno opísať pomocou nasledujúcich krokov:

Krok 1: Určte ľubovoľný vrchol ako počiatočný vrchol MST.
Krok 2: Postupujte podľa krokov 3 až 5, kým nebudú vrcholy, ktoré nie sú zahrnuté v MST (známe ako okrajový vrchol).
Krok 3: Nájdite hrany spájajúce ľubovoľný vrchol stromu s okrajovými vrcholmi.
Krok 4: Nájdite medzi týmito okrajmi minimum.
Krok 5: Pridajte zvolenú hranu do MST, ak netvorí žiadny cyklus.
Krok 6: Vráťte MST a ukončite



Poznámka: Na určenie cyklu môžeme rozdeliť vrcholy do dvoch množín [jedna množina obsahuje vrcholy zahrnuté v MST a druhá obsahuje okrajové vrcholy.]

index zoznamu
Odporúčaná prax Minimum Spanning Tree Vyskúšajte to!

Ilustrácia Primovho algoritmu:

Uvažujme nasledujúci graf ako príklad, pre ktorý musíme nájsť minimálnu kostru (MST).

Príklad grafu

Príklad grafu



Krok 1: Najprv vyberieme ľubovoľný vrchol, ktorý funguje ako počiatočný vrchol minimálneho kostry. Tu sme vybrali vrchol 0 ako počiatočný vrchol.

0 je vybratá ako počiatočný vrchol

0 je vybratá ako počiatočný vrchol

Krok 2: Všetky hrany spájajúce neúplný MST a ostatné vrcholy sú hrany {0, 1} a {0, 7}. Medzi nimi je hrana s minimálnou hmotnosťou {0, 1}. Takže zahrňte hranu a vrchol 1 do MST.

1 sa pridáva k MST

1 sa pridáva k MST

Krok 3: Hrany spájajúce neúplný MST s inými vrcholmi sú {0, 7}, {1, 7} a {1, 2}. Medzi týmito hranami je minimálna hmotnosť 8, čo je váha hrán {0, 7} a {1, 2}. Zahrňme tu hranu {0, 7} a vrchol 7 v MST. [Do MST sme mohli zahrnúť aj hranu {1, 2} a vrchol 2].

7 sa pridáva do MST

7 sa pridáva do MST

Krok 4: Hrany, ktoré spájajú neúplný MST s okrajovými vrcholmi, sú {1, 2}, {7, 6} a {7, 8}. Pridajte hranu {7, 6} a vrchol 6 v MST, pretože má najmenšiu váhu (t. j. 1).

6 sa pridáva do MST

6 sa pridáva do MST

Krok 5: Spojovacie hrany sú teraz {7, 8}, {1, 2}, {6, 8} a {6, 5}. Zahrňte hranu {6, 5} a vrchol 5 do MST, pretože hrana má medzi nimi minimálnu váhu (t. j. 2).

Zahrnúť vrchol 5 do MST

Zahrnúť vrchol 5 do MST

Krok 6: Spomedzi súčasných spojovacích hrán má hrana {5, 2} minimálnu hmotnosť. Takže zahrňte túto hranu a vrchol 2 do MST.

Zahrnúť vrchol 2 do MST

Zahrnúť vrchol 2 do MST

Krok 7: Spojovacie hrany medzi neúplným MST a ostatnými hranami sú {2, 8}, {2, 3}, {5, 3} a {5, 4}. Hrana s minimálnou hmotnosťou je hrana {2, 8}, ktorá má váhu 2. Zahrňte teda túto hranu a vrchol 8 do MST.

Pridajte vrchol 8 do MST

Pridajte vrchol 8 do MST

Krok 8: Vidíte, že hrany {7, 8} a {2, 3} majú rovnakú váhu, ktorá je minimálna. Ale 7 je už súčasťou MST. Takže vezmeme do úvahy hranu {2, 3} a zahrnieme túto hranu a vrchol 3 do MST.

Zahrnúť vrchol 3 do MST

Zahrnúť vrchol 3 do MST

Krok 9: Zostáva zahrnúť iba vrchol 4. Minimálna vážená hrana od neúplného MST po 4 je {3, 4}.

Zahrnúť vrchol 4 do MST

Zahrnúť vrchol 4 do MST

Konečná štruktúra MST je nasledovná a hmotnosť hrán MST je (4 + 8 + 1 + 2 + 4 + 2 + 7 + 9) = 37 .

Štruktúra MST vytvorená pomocou vyššie uvedeného spôsobu

Štruktúra MST vytvorená pomocou vyššie uvedeného spôsobu

Poznámka: Ak by sme v treťom kroku vybrali hranu {1, 2}, MST by vyzeralo nasledovne.

Štruktúra alternatívneho MST, ak by sme v MST vybrali hranu {1, 2}

Štruktúra alternatívneho MST, ak by sme v MST vybrali hranu {1, 2}

Ako implementovať Primov algoritmus?

Ak chcete použiť, postupujte podľa uvedených krokov Primov algoritmus uvedené vyššie na nájdenie MST grafu:

  • Vytvorte súpravu mstSet ktorý sleduje vrcholy už zahrnuté v MST.
  • Priraďte kľúčovú hodnotu všetkým vrcholom vo vstupnom grafe. Inicializujte všetky kľúčové hodnoty ako NEKONEČNÉ. Priraďte hodnotu kľúča ako 0 pre prvý vrchol, aby bol vybratý ako prvý.
  • Zatiaľ čo mstSet nezahŕňa všetky vrcholy
    • Vyberte vrchol v to tam nie je mstSet a má minimálnu hodnotu kľúča.
    • Zahrnúť v v mstSet .
    • Aktualizujte kľúčovú hodnotu všetkých susedných vrcholov v . Ak chcete aktualizovať hodnoty kľúča, iterujte cez všetky susedné vrcholy.
      • Pre každý susedný vrchol v , ak je hmotnosť hrany u-v je menšia ako predchádzajúca hodnota kľúča v , aktualizujte kľúčovú hodnotu ako váhu u-v .

Myšlienkou použitia kľúčových hodnôt je vybrať okraj s minimálnou hmotnosťou z rezať . Kľúčové hodnoty sa používajú iba pre vrcholy, ktoré ešte nie sú zahrnuté v MST, kľúčová hodnota pre tieto vrcholy označuje minimálne váhové hrany, ktoré ich spájajú so množinou vrcholov zahrnutých v MST.

Nižšie je uvedená implementácia prístupu:

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; }>

>

>

Java




// 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>

>

>

odstránenie zo zoznamu polí

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.>

>

>

Výkon

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

Analýza zložitosti Primovho algoritmu:

Časová zložitosť: O(V2), Ak je vstup graf je reprezentovaný pomocou zoznamu susedstiev , potom možno časovú zložitosť Primovho algoritmu znížiť na O(E * logV) pomocou binárnej haldy. V tejto implementácii vždy uvažujeme, že kostra začína od koreňa grafu
Pomocný priestor: O(V)

Ďalšie implementácie Primovho algoritmu:

Nižšie sú uvedené niektoré ďalšie implementácie Primovho algoritmu

  • Primov algoritmus na reprezentáciu matice susednosti – V tomto článku sme diskutovali o metóde implementácie Primovho algoritmu, ak je graf reprezentovaný maticou susedstva.
  • Primov algoritmus na reprezentáciu zoznamu susedných vzťahov – V tomto článku je popísaná implementácia Primovho algoritmu pre grafy reprezentované zoznamom susedstva.
  • Primov algoritmus pomocou prioritného frontu: V tomto článku sme diskutovali o časovo efektívnom prístupe k implementácii Primovho algoritmu.

OPTIMALIZOVANÝ PRÍSTUP ALGORITHMU PRIM:

Intuícia

  1. Maticu susednosti transformujeme na zoznam susedstva pomocou ArrayList .
  2. Potom vytvoríme triedu Pair na uloženie vrcholu a jeho váhy.
  3. Zoznam triedime na základe najnižšej hmotnosti.
  4. Vytvoríme prioritný front a zatlačíme prvý vrchol a jeho váhu vo fronte
  5. Potom už len prejdeme cez jeho hrany a najmenšiu váhu uložíme do premennej tzv rokov.
  6. Nakoniec po všetkých vrcholoch vrátime ans.

Implementácia

C++




#include> using> namespace> std;> typedef> pair<>int>,>int>>pii;> // 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>> adj[V]; // Vyplňte zoznam susedstiev hranami a ich váhami pre (int i = 0; i int u = hrany[i][0]; int v = hrany[i][1]; int wt = hrany[i][2] ]; adj[u].push_back({v, wt}); adj[v].push_back({u, wt}); navštívené pole na sledovanie vektora navštívených vrcholov navštívil(V, nepravda); // Premenná na uloženie výsledku (súčet váh hrán) int res = 0; // Začnite s vrcholom 0 pq.push({0, 0}); // Vykonajte Primov algoritmus na nájdenie Minimum Spanning Tree while(!pq.empty()){ auto p = pq.top(); pq.pop(); int wt = p.first; // Váha hrany int u = p.second; // Vrchol spojený s hranou if(navštívené[u] == true){ continue; // Preskočiť, ak je vrchol už navštívený } res += wt; // Pripočítajte váhu hrany k výsledku navštívené[u] = true; // Označte vrchol ako navštívený // Preskúmajte susedné vrcholy pre (auto v : adj[u]){ // v[0] predstavuje vrchol a v[1] predstavuje váhu hrany if(visited[v[0] ] == nepravda){ pq.push({v[1], v[0]}); // Pridaj susedný okraj do frontu priority } } } return res; // Vráti súčet váh hrán Minimum Spanning Tree } int main() { int graph[][3] = {{0, 1, 5}, {1, 2, 3}, {0, 2, 1 }}; // Volanie funkcie cout<< spanningTree(3, 3, graph) << endl; return 0; }>

>

>

Java

príklady operačného systému




// 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))>

>

html tagy

>

C#




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 = new Listint[]>>(); for (int i = 0; i { adj.Add(new List ()); } // Vyplňte zoznam susedstiev hranami a ich váhami pre (int i = 0; i { int u = hrany[i, 0]; int v = hrany[i, 1]; int wt = hrany[i, 2] ; adj[u].Add(new int[] { v, wt }); adj[v].Add(new int[] { u, wt } } // Vytvorenie prioritného frontu na uloženie hrán s ich váhami PriorityQueue<(int, int)>pq = new PriorityQueue<(int, int)>(); // Vytvorenie navštíveného poľa na sledovanie navštívených vrcholov bool[] navštívené = new bool[V]; // Premenná na uloženie výsledku (súčet váh hrán) int res = 0; // Začnite s vrcholom 0 pq.Enqueue((0, 0)); // Vykonajte Primov algoritmus na nájdenie Minimum Spanning Tree while (pq.Count> 0) { var p = pq.Dequeue(); int hm = p.Položka1; // Váha hrany int u = p.Položka2; // Vrchol spojený s hranou if (navštívené[u]) { continue; // Preskočiť, ak je vrchol už navštívený } res += wt; // Pripočítajte váhu hrany k výsledku navštívené[u] = true; // Označte vrchol ako navštívený // Preskúmajte susedné vrcholy foreach (var v in adj[u]) { // v[0] predstavuje vrchol a v[1] predstavuje váhu hrany if (!visited[v[0 ]]) { pq.Enqueue((v[1], v[0])); // Pridaj susedný okraj do frontu priority } } } return res; // Vráti súčet váh hrán Minimum Spanning Tree } public static void Main() { int[,] graf = { { 0, 1, 5 }, { 1, 2, 3 }, { 0, 2, 1 } }; // Volanie funkcie Console.WriteLine(SpanningTree(3, 3, graph)); } } // Implementácia PriorityQueue pre verejnú triedu C# PriorityQueue where T : IComparable { private List heap = new List(); public int Počet => halda.Pocet; public void Enqueue(T item) { heap.Add(item); int i = halda.Pocet - 1; while (i> 0) { int parent = (i - 1) / 2; if (hromada[nadradený].PorovnaťS(hromada[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) break; int rightChild = leftChild + 1; if (rightChild 0) leftChild = rightChild; if (hromada[rodič].PorovnaťS(hromada[ľavé dieťa])<= 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(); const wt = p[0]; // Váha hrany const u = p[1]; // Vrchol spojený s hranou if (navštívené[u]) { continue; // Preskočiť, ak je vrchol už navštívený } res += wt; // Pripočítajte váhu hrany k výsledku navštívené[u] = true; // Označte vrchol ako navštívený // Preskúmajte susedné vrcholy pre (const v of adj[u]) { // v[0] predstavuje vrchol a v[1] predstavuje váhu hrany if (!visited[v[0 ]]) { pq.enqueue([v[1], v[0]]); // Pridaj susedný okraj do frontu priority } } } return res; // Vráti súčet váh hrán Minimum Spanning Tree } // Príklad použitia const graph = [[0, 1, 5], [1, 2, 3], [0, 2, 1]]; // Volanie funkcie console.log(spanningTree(3, 3, graph));>

>

>

Výkon

4>

Analýza zložitosti Primovho algoritmu:

Časová zložitosť: O(E*log(E)), kde E je počet hrán
Pomocný priestor: O(V^2) kde V je počet vrcholov

Primov algoritmus na nájdenie minimálneho kostrového stromu (MST):

Výhody:

  1. Primov algoritmus zaručene nájde MST v prepojenom, váženom grafe.
  2. Má časovú zložitosť O(E log V) pomocou binárnej haldy alebo Fibonacciho haldy, kde E je počet hrán a V je počet vrcholov.
  3. Je to relatívne jednoduchý algoritmus na pochopenie a implementáciu v porovnaní s niektorými inými algoritmami MST.

Nevýhody:

  1. Rovnako ako Kruskalov algoritmus, aj Primov algoritmus môže byť pomalý na hustých grafoch s mnohými hranami, pretože vyžaduje iteráciu cez všetky hrany aspoň raz.
  2. Primov algoritmus sa spolieha na prioritný front, ktorý môže zaberať dodatočnú pamäť a spomaliť algoritmus na veľmi veľkých grafoch.
  3. Voľba štartovacieho uzla môže ovplyvniť výstup MST, čo nemusí byť v niektorých aplikáciách žiaduce.