Minimum spanning Tree ~kruskal algorithm
Concept of Spanning Tree:
Given an undirected graph, if any two vertices in one of its sub-graphs are interconnected and are a tree (that is, there is no ring), then this sub-graph is called a spanning tree. The spanning tree of the graph is not unique because it may have multiple sub-graphs that satisfy the conditions of the spanning tree, and the smallest spanning tree of a single graph (that is, the total weight of the spanning tree) may not be unique because there may be multiple edges with equal weights and are minimal. There are two ways to solve the minimum spanning tree: one is the Kruskal algorithm from the edge and the other is the prim algorithm from the point.
Basic idea of Kruskal algorithm:
According to the weight of the edge from small to large to sort, add it one by one into the minimum tree set U, add edge when you need to consider whether to produce a ring, the edge of the ring to continue to select the next weight of the least edge. And so on, until all points exist in the minimum tree set U.
This algorithm uses and checks the set, sorting, please refer to the code:
#include <stdio.h> #include <algorithm>using namespace std;int per[110];//Store root node int n,m;struct node//define a struct body , each of which holds two points, which is the weight value {int x;int y;int value;} Edge[10000];int CMP (node A,node b)//sort sort use, sort by weight from small to large {return a.value<b.value;} int find (int x)//Find root node and compress path {int r=x;while (r!=per[r]) r=per[r];int j,i=x;while (i!=r) {j=per[i];p er[i]=r;i=j;} return r;} a bool Join (int x,int y)//connects the point, if it can be connected, returns True, otherwise false {int fx=find (x), int fy=find (y), if (fx!=fy)//is judged to be ring {Per[fx]=fy;return true;} Elsereturn false;} int main () {while (scanf ("%d", &n), N) {m=n* (n-1)/2;//has n points, up to * (n-1)/2 edges for (int i=0;i<m;i++)//Enter two points for each edge to connect the edge weight value scanf ("%d%d%d", &edge[i].x,&edge[i].y,&edge[i].value); sort (edge,edge+m,cmp);//sorting Benquan values for (int i=1;i <=n;i++)//Initialize root node per[i]=i;int sum=0;for (int i=0;i<m;i++) {if (Join (EDGE[I].X,EDGE[I].Y)) sum+=edge[i].value;// Adds}printf ("%d\n", sum) to the weights in the tree collection, and/or outputs the weight of the minimum spanning tree}return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Minimum spanning Tree ~kruskal algorithm