Pure C language: greedy Prim algorithm generation tree source code

Source: Internet
Author: User

# Include
 
  
# Define MAX 100 # define MAXCOST 100000 int graph [MAX] [MAX]; int Prim (int graph [MAX] [MAX], int n) {/* lowcost [I] records the minimum weight of the edge whose end point is I, when lowcost [I] = 0, it indicates that end I is added to the Spanning Tree */int lowcost [MAX]; /* the mst [I] record corresponds to the start point of lowcost [I] */int mst [MAX]; int I, j, min, minid, sum = 0; /* Add node 0 to the Spanning Tree by default, and initialize Node 1 */for (I = 1; I <n; I ++) {/* the shortest path is initialized to the distance from other nodes to node 0 */lowcost [I] = graph [0] [I]; /* mark the start point of all nodes as the default node 0 */mst [I] = 0 ;} /* Add node 0 to the Spanning Tree */lowcost [0] = 0;/* at least n-1 edges are required for n nodes to form the Minimum Spanning Tree */for (I = 1; I <n; I ++) {min = MAXCOST; minid = 0;/* Find the minid of the node that meets the condition's minimum weight edge */for (j = 1; j
  
   
> M;/* initialize the graph. The distance between all nodes is infinite */for (I = 0; I
   
    
> N; graph [I] [j] = n; graph [j] [I] = n;} graph [I] [I] = MAXCOST ;} /* solve the Minimum Spanning Tree */cost = Prim (graph, m); cout <"the weight of the Minimum Spanning Tree is:" <
    
     

Related Article

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.