Minimalno vpeto drevo (MST) ali vpeto drevo z najmanjšo težo za utežen, povezan, neusmerjen graf je vpeto drevo z utežjo, ki je manjša ali enaka teži vsakega drugega vpetega drevesa. Če želite izvedeti več o minimalnem vpetem drevesu, glejte Ta članek .
Uvod v Kruskalov algoritem:
Tukaj bomo razpravljali Kruskalov algoritem da poiščete MST danega uteženega grafa.
V Kruskalovem algoritmu razvrstite vse robove danega grafa v naraščajočem vrstnem redu. Nato še naprej dodaja nove robove in vozlišča v MST, če na novo dodan rob ne tvori cikla. Najprej izbere najmanjši uteženi rob in nazadnje največji uteženi rob. Tako lahko rečemo, da naredi lokalno optimalno izbiro v vsakem koraku, da bi našel optimalno rešitev. Zato je to a Spodaj so navedeni koraki za iskanje MST z uporabo Kruskalovega algoritma:
- Vse robove razvrstite v nepadajočem vrstnem redu glede na njihovo težo.
- Izberite najmanjši rob. Preverite, ali tvori cikel z do sedaj oblikovanim vpetim drevesom. Če cikel ni oblikovan, vključite ta rob. V nasprotnem primeru zavrzite.
- Ponavljajte korak št. 2, dokler v vpetem drevesu ne bodo robovi (V-1).
2. korak uporablja Algoritem Union-Find za odkrivanje ciklov.
Zato priporočamo, da preberete naslednjo objavo kot predpogoj.
- Algoritem Union-Find | 1. sklop (zaznavanje cikla v grafu)
- Algoritem Union-Find | 2. niz (združevanje po rangu in stiskanju poti)
Kruskalov algoritem za iskanje vpetega drevesa z minimalnimi stroški uporablja pohlepen pristop. Pohlepna izbira je izbrati najmanjši rob teže, ki ne povzroči cikla v MST, izdelanem do sedaj. Naj to razumemo s primerom:
Ilustracija:
Spodaj je ilustracija zgornjega pristopa:
Vhodni graf:
Graf vsebuje 9 vozlišč in 14 robov. Tako bo minimalno oblikovano vpeto drevo imelo (9 – 1) = 8 robov.
Po razvrščanju:
Utež Vir Destinacija 1 7 6 2 8 2 2 6 5 4 0 1 4 2 5 6 8 6 7 2 3 7 7 8 8 0 7 8 1 2 9 3 4 10 5 4 enajst 1 7 14 3 5 Zdaj izberite vse robove enega za drugim z razvrščenega seznama robov
Korak 1: Izberi rob 7-6. Ne oblikuje se cikel, vključite ga.
blokiraj youtube oglase androidDodajte rob 7-6 v MST
2. korak: Izberi rob 8-2. Ne oblikuje se cikel, vključite ga.
Dodajte rob 8-2 v MST
3. korak: Izberi rob 6-5. Ne oblikuje se cikel, vključite ga.
Dodajte rob 6-5 v MST
4. korak: Izberite rob 0-1. Ne oblikuje se cikel, vključite ga.
Dodajte rob 0-1 v MST
5. korak: Izberite rob 2-5. Ne oblikuje se cikel, vključite ga.
Dodajte rob 2-5 v MST
6. korak: Izberi rob 8-6. Ker vključitev tega roba povzroči cikel, ga zavrzite. Izberite rob 2-3: Ne oblikuje se cikel, vključite ga.
Dodajte rob 2-3 v MST
7. korak: Izberi rob 7-8. Ker vključitev tega roba povzroči cikel, ga zavrzite. Izberite rob 0-7. Ne oblikuje se cikel, vključite ga.
Dodajte rob 0-7 v MST
8. korak: Izberite rob 1-2. Ker vključitev tega roba povzroči cikel, ga zavrzite. Izberite rob 3-4. Ne oblikuje se cikel, vključite ga.
Dodajte rob 3-4 v MST
Opomba: Ker je število robov, vključenih v MST, enako (V – 1), se algoritem tukaj ustavi
Spodaj je izvedba zgornjega pristopa:
C++
// C++ program for the above approach> > #include> using> namespace> std;> > // DSU data structure> // path compression + rank by union> class> DSU {> >int>* parent;> >int>* rank;> > public>:> >DSU(>int> n)> >{> >parent =>new> int>[n];> >rank =>new> int>[n];> > >for> (>int> i = 0; i parent[i] = -1; rank[i] = 1; } } // Find function int find(int i) { if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } // Union function void unite(int x, int y) { int s1 = find(x); int s2 = find(y); if (s1 != s2) { if (rank[s1] parent[s1] = s2; } else if (rank[s1]>rank[s2]) { parent[s2] = s1; } else { parent[s2] = s1; rang[s1] += 1; } } } }; class Graph { vectorint>> edgelist; int V; public: Graph(int V) { this->V = V; } // Funkcija za dodajanje roba v graf void addEdge(int x, int y, int w) { edgelist.push_back({ w, x, y }); } void kruskals_mst() { // Razvrsti vse robove sort(edgelist.begin(), edgelist.end()); // Inicializacija DSU DSU s(V); int ans = 0; cout<< 'Following are the edges in the ' 'constructed MST' << endl; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; // Take this edge in MST if it does // not forms a cycle if (s.find(x) != s.find(y)) { s.unite(x, y); ans += w; cout << x << ' -- ' << y << ' == ' << w << endl; } } cout << 'Minimum Cost Spanning Tree: ' << ans; } }; // Driver code int main() { Graph g(4); g.addEdge(0, 1, 10); g.addEdge(1, 3, 15); g.addEdge(2, 3, 4); g.addEdge(2, 0, 6); g.addEdge(0, 3, 5); // Function call g.kruskals_mst(); return 0; }> |
>
>
C
// C code to implement Kruskal's algorithm> > #include> #include> > // Comparator function to use in sorting> int> comparator(>const> void>* p1,>const> void>* p2)> {> >const> int>(*x)[3] = p1;> >const> int>(*y)[3] = p2;> > >return> (*x)[2] - (*y)[2];> }> > // Initialization of parent[] and rank[] arrays> void> makeSet(>int> parent[],>int> rank[],>int> n)> {> >for> (>int> i = 0; i parent[i] = i; rank[i] = 0; } } // Function to find the parent of a node int findParent(int parent[], int component) { if (parent[component] == component) return component; return parent[component] = findParent(parent, parent[component]); } // Function to unite two sets void unionSet(int u, int v, int parent[], int rank[], int n) { // Finding the parents u = findParent(parent, u); v = findParent(parent, v); if (rank[u] parent[u] = v; } else if (rank[u]>rank[v]) { parent[v] = u; } else { parent[v] = u; // Ker se rang poveča, če // sta ranga dveh nizov enaka rank[u]++; } } // Funkcija za iskanje MST void kruskalAlgo(int n, int edge[n][3]) { // Najprej razvrstimo matriko robov v naraščajočem vrstnem redu // tako da lahko dostopamo do najmanjših razdalj/stroškov qsort(edge , n, sizeof(edge[0]), primerjalnik); int nadrejeni [n]; int rang [n]; // Funkcija za inicializacijo parent[] in rank[] makeSet(parent, rank, n); // Za shranjevanje minimalnih stroškov int minCost = 0; printf( 'Sledijo robovi v konstruiranem MST
'); for (int i = 0; i int v1 = findParent(parent, edge[i][0]); int v2 = findParent(parent, edge[i][1]); int wt = edge[i][2] ; // Če so starši različni, to // pomeni, da so v različnih nizih, zato jih združimo if (v1 != v2) { unionSet(v1, v2, parent, rank, n); minCost += wt; '%d -- %d == %d
', edge[i][0], edge[i][1], wt } } printf('Minimalno vpeto drevo stroškov: %d); n', minCost); // Koda gonilnika int main() { int edge[5][3] = { { 0, 1, 10 }, { 0, 2, 6 } , { 1, 3, 15 }, { 2, 3, 4 }; kruskalAlgo(5, edge); return 0;> |
>
>
Java
// Java program for Kruskal's algorithm> > import> java.util.ArrayList;> import> java.util.Comparator;> import> java.util.List;> > public> class> KruskalsMST {> > >// Defines edge structure> >static> class> Edge {> >int> src, dest, weight;> > >public> Edge(>int> src,>int> dest,>int> weight)> >{> >this>.src = src;> >this>.dest = dest;> >this>.weight = weight;> >}> >}> > >// Defines subset element structure> >static> class> Subset {> >int> parent, rank;> > >public> Subset(>int> parent,>int> rank)> >{> >this>.parent = parent;> >this>.rank = rank;> >}> >}> > >// Starting point of program execution> >public> static> void> main(String[] args)> >{> >int> V =>4>;> >List graphEdges =>new> ArrayList(> >List.of(>new> Edge(>0>,>1>,>10>),>new> Edge(>0>,>2>,>6>),> >new> Edge(>0>,>3>,>5>),>new> Edge(>1>,>3>,>15>),> >new> Edge(>2>,>3>,>4>)));> > >// Sort the edges in non-decreasing order> >// (increasing with repetition allowed)> >graphEdges.sort(>new> Comparator() {> >@Override> public> int> compare(Edge o1, Edge o2)> >{> >return> o1.weight - o2.weight;> >}> >});> > >kruskals(V, graphEdges);> >}> > >// Function to find the MST> >private> static> void> kruskals(>int> V, List edges)> >{> >int> j =>0>;> >int> noOfEdges =>0>;> > >// Allocate memory for creating V subsets> >Subset subsets[] =>new> Subset[V];> > >// Allocate memory for results> >Edge results[] =>new> Edge[V];> > >// Create V subsets with single elements> >for> (>int> i =>0>; i subsets[i] = new Subset(i, 0); } // Number of edges to be taken is equal to V-1 while (noOfEdges 1) { // Pick the smallest edge. And increment // the index for next iteration Edge nextEdge = edges.get(j); int x = findRoot(subsets, nextEdge.src); int y = findRoot(subsets, nextEdge.dest); // If including this edge doesn't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { results[noOfEdges] = nextEdge; union(subsets, x, y); noOfEdges++; } j++; } // Print the contents of result[] to display the // built MST System.out.println( 'Following are the edges of the constructed MST:'); int minCost = 0; for (int i = 0; i System.out.println(results[i].src + ' -- ' + results[i].dest + ' == ' + results[i].weight); minCost += results[i].weight; } System.out.println('Total cost of MST: ' + minCost); } // Function to unite two disjoint sets private static void union(Subset[] subsets, int x, int y) { int rootX = findRoot(subsets, x); int rootY = findRoot(subsets, y); if (subsets[rootY].rank subsets[rootY].parent = rootX; } else if (subsets[rootX].rank subsets[rootX].parent = rootY; } else { subsets[rootY].parent = rootX; subsets[rootX].rank++; } } // Function to find parent of a set private static int findRoot(Subset[] subsets, int i) { if (subsets[i].parent == i) return subsets[i].parent; subsets[i].parent = findRoot(subsets, subsets[i].parent); return subsets[i].parent; } } // This code is contributed by Salvino D'sa> |
>
>
Python3
# Python program for Kruskal's algorithm to find> # Minimum Spanning Tree of a given connected,> # undirected and weighted graph> > > # Class to represent a graph> class> Graph:> > >def> __init__(>self>, vertices):> >self>.V>=> vertices> >self>.graph>=> []> > ># Function to add an edge to graph> >def> addEdge(>self>, u, v, w):> >self>.graph.append([u, v, w])> > ># A utility function to find set of an element i> ># (truly uses path compression technique)> >def> find(>self>, parent, i):> >if> parent[i] !>=> i:> > ># Reassignment of node's parent> ># to root node as> ># path compression requires> >parent[i]>=> self>.find(parent, parent[i])> >return> parent[i]> > ># A function that does union of two sets of x and y> ># (uses union by rank)> >def> union(>self>, parent, rank, x, y):> > ># Attach smaller rank tree under root of> ># high rank tree (Union by Rank)> >if> rank[x] parent[x] = y elif rank[x]>rank[y]: parent[y] = x # Če so rangi enaki, naredi enega kot koren # in povečaj njegov rang za enega drugega: parent[y] = x rank[x] += 1 # Glavna funkcija za konstruiranje MST # z uporabo Kruskalovega algoritma def KruskalMST(self): # To bo shranilo rezultat MST = [] # Indeksna spremenljivka, uporabljena za razvrščene robove i = 0 # Indeksna spremenljivka, uporabljena za rezultat[] e = 0 # Razvrsti vse robove v # nepadajočem vrstnem redu njihove # teže self.graph = sorted(self.graph, key=lambda item: item[2]) parent = [] rank = [] # Ustvari podmnožice V z enojnimi elementi za vozlišče v obsegu (self.V): parent.append(node) rank.append(0) # Število robov, ki jih je treba prevzeti, je manjše od V-1, medtem ko e |
>
if else if else if java
>
C#
// C# Code for the above approach> > using> System;> > class> Graph {> > >// A class to represent a graph edge> >class> Edge : IComparable {> >public> int> src, dest, weight;> > >// Comparator function used for sorting edges> >// based on their weight> >public> int> CompareTo(Edge compareEdge)> >{> >return> this>.weight - compareEdge.weight;> >}> >}> > >// A class to represent> >// a subset for union-find> >public> class> subset {> >public> int> parent, rank;> >};> > >// V->št. oglišč & E->št.robov> >int> V, E;> > >// Collection of all edges> >Edge[] edge;> > >// Creates a graph with V vertices and E edges> >Graph(>int> v,>int> e)> >{> >V = v;> >E = e;> >edge =>new> Edge[E];> >for> (>int> i = 0; i edge[i] = new Edge(); } // A utility function to find set of an element i // (uses path compression technique) int find(subset[] subsets, int i) { // Find root and make root as // parent of i (path compression) if (subsets[i].parent != i) subsets[i].parent = find(subsets, subsets[i].parent); return subsets[i].parent; } // A function that does union of // two sets of x and y (uses union by rank) void Union(subset[] subsets, int x, int y) { int xroot = find(subsets, x); int yroot = find(subsets, y); // Attach smaller rank tree under root of // high rank tree (Union by Rank) if (subsets[xroot].rank subsets[xroot].parent = yroot; else if (subsets[xroot].rank>podmnožice[yroot].rank) podmnožice[yroot].parent = xroot; // Če so rangi enaki, naredite enega kot koren // in povečajte njegov rang za enega { subsets[yroot].parent = xroot; podmnožice[xroot].rank++; } } // Glavna funkcija za konstruiranje MST // z uporabo Kruskalovega algoritma void KruskalMST() { // To bo shranilo // rezultat MST Edge[] rezultat = new Edge[V]; // Indeksna spremenljivka, uporabljena za rezultat [] int e = 0; // Indeksna spremenljivka, ki se uporablja za razvrščene robove int i = 0; for (i = 0; i result[i] = new Edge(); // Razvrsti vse robove v nepadajočem // vrstnem redu glede na njihovo težo. Če nam // ni dovoljeno spreminjati danega grafa, lahko ustvarimo // kopija matrike robov Array.Sort(edge); // Dodelitev pomnilnika za ustvarjanje podnaborov V podnaborov [] podnaborov [V]; for (i = 0; i podnaborov [i] = nov podnaborov () ; // Ustvari V podmnožice s posameznimi elementi za (int v = 0; v podmnožice [v].parent = v; podmnožice [v].rank = 0; } i = 0; // Število robov, ki jih je treba vzeti, je enako na V-1 medtem ko (e // Izberi najmanjši rob. In povečaj // indeks za naslednjo iteracijo Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // Če vključitev tega roba ne povzroči cikla, // ga vključite v rezultat in povečajte indeks // rezultata za naslednji rob if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } } // Natisni vsebino rezultata [] za prikaz // zgrajene MST Console.WriteLine('Sledijo robovi v ' + ' zgrajen MST'); int minimumCost = 0; for (i = 0; i Console.WriteLine(result[i].src + ' -- ' + result[i].dest + ' == ' + result[i].weight); minimumCost += result[i].weight; } Console.WriteLine('Minimum Cost Spanning Tree:' + minimumCost(); // koda gonilnika public static(String[] args) { int V = 5; Graph graph = new Graph(V, E); // dodaj rob graph.edge[0].src = 0; graph.edge[0].weight = 10; // dodaj rob graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 6 ; // dodaj rob 0-3 graph.edge [2].src = 0; graph.edge [2].weight = 5; // dodaj graf 1-3. edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 15; // dodaj rob 2-3 graph.edge[4].src = 2; .edge[4].dest = 3; graph.edge[4].weight = 4; // Funkcijski klic graph.KruskalMST(); } // To kodo je prispeval Aakash Hasija> |
>
>
Javascript
> // JavaScript implementation of the krushkal's algorithm.> > function> makeSet(parent,rank,n)> {> >for>(let i=0;i { parent[i]=i; rank[i]=0; } } function findParent(parent,component) { if(parent[component]==component) return component; return parent[component] = findParent(parent,parent[component]); } function unionSet(u, v, parent, rank,n) { //this function unions two set on the basis of rank //as shown below u=findParent(parent,u); v=findParent(parent,v); if(rank[u] { parent[u]=v; } else if(rank[u] { parent[v]=u; } else { parent[v]=u; rank[u]++;//since the rank increases if the ranks of two sets are same } } function kruskalAlgo(n, edge) { //First we sort the edge array in ascending order //so that we can access minimum distances/cost edge.sort((a, b)=>{ return a[2] - b[2]; }) //vgrajena funkcija hitrega razvrščanja je priložena stdlib.h //pojdite na https://www.techcodeview.com Razvrščanje robov traja O(E * logE) časa. Po razvrščanju ponovimo vse robove in uporabimo algoritem find-union. Operaciji iskanja in združevanja lahko trajata največ O(logV) časa. Celotna kompleksnost je torej čas O(E * logE + E * logV). Vrednost E je lahko največ O(V2), zato sta O(logV) in O(logE) enaka. Zato je skupna časovna kompleksnost O(E * logE) ali O(E*logV) Pomožni prostor: O(V + E), kjer je V število vozlišč in E število robov v grafu. Ta članek je zbral Aashish Barnwal, pregledala pa ga je ekipa techcodeview.com.> |








