See Data structure write code (42) minimum spanning tree

Source: Internet
Author: User

First, some conceptual questions are given:

1. Spanning tree: A minimal connected sub-graph of a connected graph of n vertices. It contains n vertices, but only the n-1 edges, and there is no loop.

2. Minimum spanning tree: A weighted undirected graph to find out the spanning tree with the least sum of the weights of each edge, called the minimum spanning tree.

Therefore, the minimum spanning tree should be satisfied first: 1. The first is the no-show Figure 2. Must be a connected graph (any two vertices up to) 3. With Right

Simply put, it must be a connected network.


In order to find the minimum spanning tree, the data structure of Min gives two methods: Primm algorithm and Kruskal algorithm.

Primm algorithm:



Kruskal algorithm:


The Kruskal algorithm discards the edges because of the resulting loop.


since the Primm algorithm needs to find a lot of weights between the two vertices, the adjacency matrix representation of the graph is the most suitable and the time complexity is O (1). Other representations need to traverse the linked list, which is O (Len), and Len is the table length of the linked list.


Full code project File Web address: Click to open link


The code for the PRIMM algorithm is given below:

//Primm minimum spanning tree algorithm struct lowcost//minimum cost array {char tovex;//vertex name int cost;//cost};int minlowcost ( Lowcost * Array,int vexnum) {int min = infinity;int k = -1;for (int i = 0; i < Vexnum; i++) {int cost = Array[i].cost;if (Cost < min && cost! = 0) {min = array[i].cost;k = i;}} return k;} void Minispantree_prim (Mgraph g,char vex) {lowcost Lcarray[max_vertex_num];int k = graphlocation (G,vex); for (int i = 0; I & Lt G.vexnum; i++) {//Initialize Lcarraylcarray[i].tovex = Vex;lcarray[i].cost = G.arcs[k][i].adj;} Lcarray[k].cost = 0;//adds k to the collection uprintf ("-----------minimum spanning tree----------------\ n"); for (int i = 1; i < G.vexnum; i++) {//Total n 1 Plays: K = Minlowcost (lcarray,g.vexnum);p rintf ("%c-%c weights are%d\n", lcarray[k].tovex,g.vexs[k],lcarray[k].cost); LcArray[k]. Cost = 0;//adds k to the set U. for (int i = 0; i < G.vexnum; i++) {//Get new minimum price int min = lcarray[i].cost;if (min! = 0 && ; G.arcs[k][i].adj < min) {//Do not participate in the collection u Lcarray[i].tovex = G.vexs[k];lcarray[i].cost = G.arcs[k][i].adj;}}} 

It can be seen from the code that the time complexity of the PRIMM algorithm is O (n*n), and n is the vertex number, which is suitable for the dense graph of edges.


The Kruskal algorithm code is as follows:

The specific idea is: all the edges of the graph into the array from small to large order, and then in the order of the sequence to take n-1 edge, (n is the vertex tree), discard will cause the side of the loop, the discarded edge is not counted in n-1 edge.

The Kruskal algorithm is suitable for multiple adjacency tables, the adjacency matrix array initialization is O (n * n/2), n is the vertex number, the adjacency table is not suitable for all edges, and the Multilink table is initialized to O (e), E is the number of edges.

The following code does not use a multiple adjacency table, with the adjacency matrix.

Kruskal minimum spanning tree. struct edge//edge set {int Begin;int end;int cost;};/ /Quick sort Edge Set array void QSort (Edge * Array,int Left,int right) {if (left >= right) {return;} int i = Left;int J = right; Edge base = Array[i];while (J! = i) {while (J > I && array[j].cost >= base.cost) j--;while (J > I &&am P Array[i].cost <= Base.cost) i++;if (J > i) {Edge temp = array[j];array[j] = array[i];array[i] = temp;}} Array[left] = Array[i];array[i] = Base;qsort (array,left,i-1); QSort (array,i+1,right);} The adjacency matrix is converted into an array of edge sets and sorted from small to large in a quick order. void Coverttoedgearray (mgraph G,edge * edgearray) {//Initialize the edge set array int count = 0;for According to the upper triangular portion of the matrix ( int i = 0; i < G.vexnum; i++) {for (int j = i+1; J < G.vexnum; J + +) {int cost = G.ARCS[I][J].ADJ;IF (cost! = INFINITY) {edgearray[count].begin = i; Edgearray[count].end = J;edgearray[count].cost = cost;count++;}}} Fast sort Edge Set array qsort (EDGEARRAY,0,G.ARCNUM-1);} int getParent (int k,int * parent) {while (Parent[k] > 0) {k = parent[k];} return k;} void Minispantree_cruskal (Mgraph g) {printf ("\ n-----------Kruskal minimum spanning tree----------------\ n "); Edge edgearray[max_edge_num];//edge set. int Parent[max_vertex_num] = {0};coverttoedgearray (g,edgearray);// The edges of the adjacency matrix are deposited into the array in small to large order. int times = 0;for (int i = 0; i < G.arcnum; i++) {Edge edge = edgearray[i];int P1 = getParent (edge.b egin,parent); int p2 = getParent (edge.end,parent), if (P1! = p2) {///parent node not present, loop//parent[edge.begin] = Edge.end;parent[p1] = p2;printf ("%c-%c weight is%d\n", g.vexs[edge.begin],g.vexs[edge.end],edge.cost); Times++;if (Times >= g.vexnum-1) { return;}}}

The time complexity of the Kruskal algorithm is O (Eloge), and E is the number of sides of the graph, which is suitable for the sparse graph of edges.

Run:


The non-net above, according to the book below the picture, but the vertex name (V1,V2...V6) to change (ABCDEF)



See Data structure write code (42) minimum spanning tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.