logo

Primův algoritmus pro minimální spanningový strom (MST)

Úvod do Primova algoritmu:

diskutovali jsme Kruskalův algoritmus pro Minimum Spanning Tree . Stejně jako Kruskalův algoritmus je i Primův algoritmus a Chamtivý algoritmus . Tento algoritmus vždy začíná jedním uzlem a pohybuje se přes několik sousedních uzlů, aby prozkoumal všechny spojené hrany podél cesty.

Algoritmus začíná prázdným kostrou. Cílem je zachovat dvě sady vrcholů. První sada obsahuje vrcholy již zahrnuté v MST a druhá sada obsahuje vrcholy ještě nezahrnuté. V každém kroku zváží všechny hrany, které spojují obě sady, a vybere z těchto hran hranu s minimální hmotností. Po vybrání hrany přesune druhý koncový bod hrany do sady obsahující MST.

Skupina hran, která spojuje dvě sady vrcholů v grafu, se nazývá řez v teorii grafů . Takže v každém kroku Primova algoritmu najděte řez, vyberte hranu s minimální váhou řezu a zahrňte tento vrchol do MST Set (množina, která obsahuje již zahrnuté vrcholy).



Jak funguje Primův algoritmus?

Fungování Primova algoritmu lze popsat pomocí následujících kroků:

Krok 1: Určete libovolný vrchol jako počáteční vrchol MST.
Krok 2: Postupujte podle kroků 3 až 5, dokud nebudou vertexy, které nejsou zahrnuty v MST (známé jako okrajový vertex).
Krok 3: Najděte hrany spojující libovolný vrchol stromu s okrajovými vrcholy.
Krok 4: Najděte mezi těmito hranami minimum.
Krok 5: Přidejte vybranou hranu do MST, pokud netvoří žádný cyklus.
Krok 6: Vraťte MST a ukončete

Poznámka: Pro určení cyklu můžeme rozdělit vrcholy do dvou množin [jedna množina obsahuje vertexy zahrnuté v MST a druhá obsahuje okrajové vertexy.]

Doporučená praxe Minimální Spanning Tree Vyzkoušejte to!

Ilustrace Primova algoritmu:

Zvažte následující graf jako příklad, pro který potřebujeme najít minimální kostru (MST).

Příklad grafu

Příklad grafu

Krok 1: Nejprve vybereme libovolný vrchol, který funguje jako počáteční vrchol minimální kostry. Zde máme vybraný vrchol 0 jako počáteční vrchol.

0 je vybrán jako počáteční vrchol

0 je vybrán jako počáteční vrchol

Krok 2: Všechny hrany spojující neúplný MST a další vrcholy jsou hrany {0, 1} a {0, 7}. Mezi těmito dvěma je hrana s minimální hmotností {0, 1}. Zahrňte tedy hranu a vrchol 1 do MST.

1 se přidává k MST

1 se přidává k MST

Krok 3: Hrany spojující neúplný MST s ostatními vrcholy jsou {0, 7}, {1, 7} a {1, 2}. Mezi těmito hranami je minimální hmotnost 8, což je hran {0, 7} a {1, 2}. Zahrneme zde hranu {0, 7} a vrchol 7 v MST. [Mohli jsme také zahrnout hranu {1, 2} a vrchol 2 do MST].

java math.random
7 je přidán do MST

7 je přidán do MST

Krok 4: Hrany, které spojují neúplný MST s okrajovými vrcholy, jsou {1, 2}, {7, 6} a {7, 8}. Přidejte hranu {7, 6} a vrchol 6 v MST, protože má nejmenší váhu (tj. 1).

6 je přidán do MST

6 je přidán do MST

Krok 5: Spojovací hrany jsou nyní {7, 8}, {1, 2}, {6, 8} a {6, 5}. Zahrňte do MST hranu {6, 5} a vrchol 5, protože hrana má mezi nimi minimální váhu (tj. 2).

Zahrnout vrchol 5 do MST

Zahrnout vrchol 5 do MST

Krok 6: Mezi aktuálními spojovacími hranami má hrana {5, 2} minimální váhu. Takže zahrňte tuto hranu a vrchol 2 do MST.

Zahrnout vrchol 2 do MST

Zahrnout vrchol 2 do MST

Krok 7: Spojovací hrany mezi neúplným MST a ostatními hranami jsou {2, 8}, {2, 3}, {5, 3} a {5, 4}. Hrana s minimální váhou je hrana {2, 8}, která má váhu 2. Zahrňte tedy tuto hranu a vrchol 8 do MST.

Přidejte vrchol 8 do MST

Přidejte vrchol 8 do MST

Krok 8: Podívejte se, že hrany {7, 8} a {2, 3} mají stejnou váhu, která je minimální. Ale 7 je již součástí MST. Budeme tedy uvažovat hranu {2, 3} a zahrneme tuto hranu a vrchol 3 do MST.

Zahrnout vrchol 3 do MST

Zahrnout vrchol 3 do MST

Krok 9: Zbývá zahrnout pouze vrchol 4. Minimální vážená hrana od neúplného MST do 4 je {3, 4}.

Zahrnout vrchol 4 do MST

Zahrnout vrchol 4 do MST

Konečná struktura MST je následující a váha hran MST je (4 + 8 + 1 + 2 + 4 + 2 + 7 + 9) = 37 .

Struktura MST vytvořená pomocí výše uvedené metody

Struktura MST vytvořená pomocí výše uvedené metody

Poznámka: Pokud bychom ve třetím kroku vybrali hranu {1, 2}, pak by MST vypadal následovně.

Struktura alternativního MST, pokud bychom v MST vybrali hranu {1, 2}

Struktura alternativního MST, pokud bychom v MST vybrali hranu {1, 2}

Jak implementovat Primův algoritmus?

Chcete-li použít, postupujte podle uvedených kroků Primův algoritmus výše uvedené pro nalezení MST grafu:

  • Vytvořte sadu mstSet který sleduje vrcholy již zahrnuté v MST.
  • Přiřaďte klíčovou hodnotu všem vrcholům ve vstupním grafu. Inicializujte všechny hodnoty klíče jako INFINITE. Přiřaďte hodnotu klíče jako 0 pro první vrchol, aby byl vybrán jako první.
  • Zatímco mstSet nezahrnuje všechny vrcholy
    • Vyberte vrchol v která tam není mstSet a má minimální hodnotu klíče.
    • Zahrnout v v mstSet .
    • Aktualizujte hodnotu klíče všech sousedních vrcholů v . Chcete-li aktualizovat hodnoty klíče, iterujte přes všechny sousední vrcholy.
      • Pro každý sousední vrchol v , je-li hmotnost hrany u-v je menší než předchozí hodnota klíče v , aktualizujte hodnotu klíče jako váhu u-v .

Myšlenka použití klíčových hodnot je vybrat hranu minimální hmotnosti z střih . Hodnoty klíče se používají pouze pro vrcholy, které ještě nejsou zahrnuty v MST, hodnota klíče pro tyto vrcholy označuje minimální váhové hrany, které je spojují se sadou vrcholů zahrnutých v MST.

Níže je implementace pří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; }>

>

>

scan.nextstring java

Jáva




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

>

>

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ýstup

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

Analýza složitosti Primova algoritmu:

Časová náročnost: O(V2), Pokud je vstup graf je znázorněn pomocí seznamu sousedství , pak lze časovou složitost Primova algoritmu snížit na O(E * logV) pomocí binární haldy. V této implementaci vždy uvažujeme, že kostra začíná od kořene grafu
Pomocný prostor: O(V)

Další implementace Primova algoritmu:

Níže jsou uvedeny některé další implementace Primova algoritmu

  • Primův algoritmus pro reprezentaci matice sousedství – V tomto článku jsme diskutovali o metodě implementace Primova algoritmu, pokud je graf reprezentován maticí sousedství.
  • Primův algoritmus pro reprezentaci seznamu sousedství – V tomto článku je popsána implementace Prim’s Algorithm pro grafy reprezentované seznamem sousedství.
  • Primův algoritmus využívající prioritní frontu: V tomto článku jsme diskutovali o časově efektivním přístupu k implementaci Primova algoritmu.

OPTIMALIZOVANÝ PŘÍSTUP ALGORITHMU PRIM:

Intuice

  1. Matici sousednosti transformujeme na seznam sousedství pomocí ArrayList .
  2. Poté vytvoříme třídu Pair pro uložení vrcholu a jeho váhy.
  3. Seznam třídíme na základě nejnižší váhy.
  4. Vytvoříme prioritní frontu a vložíme první vrchol a jeho váhu ve frontě
  5. Pak už jen projíždíme jeho hrany a nejmenší váhu uložíme do proměnné tzv let.
  6. Nakonec po všech vrcholech vrátíme ans.

Implementace

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 seznam sousedství hranami a jejich vahami pro (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 pro sledování vektoru navštívených vrcholů navštívil(V, nepravda); // Proměnná pro uložení výsledku (součet vah hran) int res = 0; // Začít s vrcholem 0 pq.push({0, 0}); // Proveďte Primův algoritmus k nalezení minimálního kostrového stromu while(!pq.empty()){ auto p = pq.top(); pq.pop(); int hm = p.první; // Váha hrany int u = p.second; // Vrchol spojený s hranou if(visited[u] == true){ continue; // Přeskočit, pokud je vrchol již navštíven } res += wt; // Přidání váhy hrany k výsledku navštíveno[u] = true; // Označte vrchol jako navštívený // Prozkoumejte sousední vrcholy pro (auto v: adj[u]){ // v[0] představuje vrchol a v[1] představuje váhu hrany if(visited[v[0] ] == false){ pq.push({v[1], v[0]}); // Přidání sousedního okraje do prioritní fronty } } } return res; // Vrátí součet vah hran minimální kostry } int main() { int graf[][3] = {{0, 1, 5}, {1, 2, 3}, {0, 2, 1 }}; // Volání funkce cout<< spanningTree(3, 3, graph) << endl; return 0; }>

>

>

Jáva




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




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 seznam sousedství hranami a jejich vahami pro (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 } } // Vytvoří prioritní frontu pro ukládání hran s jejich vahami PriorityQueue<(int, int)>pq = nová fronta priority<(int, int)>(); // Vytvoří navštívené pole pro sledování navštívených vrcholů bool[] navštíveno = new bool[V]; // Proměnná pro uložení výsledku (součet vah hran) int res = 0; // Začít s vrcholem 0 pq.Enqueue((0, 0)); // Proveďte Primův algoritmus k nalezení minimálního kostrového stromu while (pq.Count> 0) { var p = pq.Dequeue(); int hm = p.Položka1; // Váha hrany int u = p.Item2; // Vrchol spojený s hranou if (navštíveno[u]) { pokračovat; // Přeskočit, pokud je vrchol již navštíven } res += wt; // Přidání váhy hrany k výsledku navštíveno[u] = true; // Označte vrchol jako navštívený // Prozkoumejte sousední vrcholy foreach (var v in adj[u]) { // v[0] představuje vrchol a v[1] představuje váhu hrany if (!visited[v[0 ]]) { pq.Enqueue((v[1], v[0])); // Přidání sousedního okraje do prioritní fronty } } } return res; // Vrátí součet vah hran Minimum Spanning Tree } public static void Main() { int[,] graf = { { 0, 1, 5 }, { 1, 2, 3 }, { 0, 2, 1 } }; // Volání funkce Console.WriteLine(SpanningTree(3, 3, graph)); } } // Implementace PriorityQueue pro veřejnou třídu C# PriorityQueue where T : IComparable { private List heap = new List(); public int Počet => halda.Počet; public void Enqueue(T item) { heap.Add(item); int i = halda.Počet - 1; while (i> 0) { int rodič = (i - 1) / 2; if (hromada[rodič].PorovnatTo(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č].PorovnatTo(hromada[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(); const wt = p[0]; // Váha hrany const u = p[1]; // Vrchol spojený s hranou if (navštíveno[u]) { pokračovat; // Přeskočit, pokud je vrchol již navštíven } res += wt; // Přidání váhy hrany k výsledku navštíveno[u] = true; // Označte vrchol jako navštívený // Prozkoumejte sousední vrcholy pro (const v of adj[u]) { // v[0] představuje vrchol a v[1] představuje váhu hrany if (!visited[v[0 ]]) { pq.enqueue([v[1], v[0]]); // Přidání sousedního okraje do prioritní fronty } } } return res; // Vrátí součet vah hran Minimum Spanning Tree } // Příklad použití const graph = [[0, 1, 5], [1, 2, 3], [0, 2, 1]]; // Volání funkce console.log(spanningTree(3, 3, graph));>

>

jsou to zpěváci
>

Výstup

4>

Analýza složitosti Primova algoritmu:

Časová náročnost: O(E*log(E)) kde E je počet hran
Pomocný prostor: O(V^2) kde V je počet vrcholu

Primův algoritmus pro nalezení minimálního spanning tree (MST):

výhody:

  1. Primův algoritmus zaručeně najde MST v spojeném váženém grafu.
  2. Má časovou složitost O(E log V) pomocí binární haldy nebo Fibonacciho haldy, kde E je počet hran a V je počet vrcholů.
  3. Je to relativně jednoduchý algoritmus na pochopení a implementaci ve srovnání s některými jinými MST algoritmy.

Nevýhody:

  1. Stejně jako Kruskalův algoritmus může být Primův algoritmus pomalý na hustých grafech s mnoha hranami, protože vyžaduje iteraci přes všechny hrany alespoň jednou.
  2. Primův algoritmus se spoléhá na prioritní frontu, která může zabírat další paměť a zpomalit algoritmus na velmi velkých grafech.
  3. Volba počátečního uzlu může ovlivnit výstup MST, což nemusí být v některých aplikacích žádoucí.