Minimum spanning tree
Given an undirected graph, if any of the two vertices in one of its sub-graphs are interconnected and are a tree, then this tree is called the spanning tree, and if the edge has the right value, then the margin and the smallest spanning tree is called the minimum spanning tree .
The common algorithm to solve the minimum spanning tree is Kruskal algorithm and prim algorithm, whether the spanning tree exists and whether the graph is connected is equivalent , so it is assumed that the graph is connected.
Prim algorithm
Suppose there is a number t that contains only one vertex V, and then greedily chooses the edge of the smallest weighted value connected between t and the other vertices and adds it to T. The minimum spanning tree can be obtained by continuing this operation (contradiction proof available)
Code that does not use heap optimization
intEG[MAX_V][MAX_V];intMINCOST[MAX_V];BOOLUSED[MAX_V];intVintPrim () { for(inti =0; i < V; i + +) {Used[i] =false; Mincost = INF; } mincost[0] =0;intres =0; while(true) {intv =-1; for(inti =0; I < V; i + +) {//Choose one of the least right from the selected edge if(!used[i]) {if(v = =-1|| Mincost[i] < mincost[v]) v = i; } }if(v = =-1) Break; USED[V] =true; Res + = Mincost[v]; for(inti =0; i < V; i + +) {Mincost[i] =min(Mincost[i],eg[v][i]); } }returnRes;}
The prim algorithm can also be maintained using the priority queue (heap), where the complexity can reach O (| E|log| v|)
Kruskal algorithm
look at the weight of the edges from small to large, and if you do not create a circle (the heavy edges are counted), add the current edge to the spanning tree.
Determines whether the set can be used and checked in a connected component.
The entire Kruskal algorithm complexity O (| E|log| v|)
struct Edge {int from , To,cost;}; bool cmp (Edge A,edge b) {return a.cost < B.cost;} Edge Eg[max_e]; int v,e; int Kruskal () {sort (eg,eg+e,cmp); Init_union_find (v); int res = 0 ; //minimum spanning tree weights for (int i = 0 ; i < E; i + +) {Edge e = eg[i]; if (!same (E.from , E.to)) {Unite (E.from , e.to); Res + = E.cost; } }}
Minimum spanning tree prim algorithm Kruskal algorithm