Data Structure and algorithm problems sdut OJ 2144 minimal spanning tree

Source: Internet
Author: User
There are n cities, some of which can be built between cities, and the cost of building different roads is different. Now, we want to know how much it will cost to build a highway to connect all cities so that we can start in any city and reach any other city.

The input contains multiple groups of data in the following format.

The first line contains two integers, n m, representing the number of cities and the number of roads that can be built. (N <= 100) the remaining m rows have three positive integers, a B c, indicating that a highway can be built between City A and City B at the cost of C. Each output group occupies one row, with only the minimum output cost. Sample Input
3 21 2 11 3 1
Sample output
2


# Include <iostream> using namespace STD; const int intifiy = 65535; typedef struct graph {int Vex [200]; int adj [200] [200]; int numvex, numedge ;} graph; void create (graph * g) {int W, J, I, K; CIN> G-> numvex> G-> numedge; for (I = 1; I <G-> numedge; I ++) for (j = 1; j <G-> numedge; j ++) g-> adj [I] [J] = intifiy; for (I = 1; I <= G-> numvex; I ++) g-> Vex [I] = I; for (k = 0; k <G-> numedge; k ++) {CIN> I> j> W; g-> adj [I] [J] = W; G-> adj [J] [I] = G-> adj [I] [J] ;}} void prim (graph * g) {int min, I, K, J, num = 0; int lowcost [200]; int adj [200]; lowcost [1] = 0; // reserve the right value. adj [1] = 1; // The forward of each node. For (I = 2; I <= G-> numvex; I ++) {lowcost [I] = G-> adj [1] [I]; adj [I] = 0;} for (I = 2; I <= G-> numvex; I ++) {min = intifiy; j = 2; while (j <= G-> numvex) {If (lowcost [J]! = 0 & lowcost [J] <min) {min = lowcost [J]; k = J;} J ++; num + = min ;} lowcost [k] = 0; for (I = 2; I <= G-> numvex; I ++) {If (lowcost [I]! = 0 & lowcost [I]> G-> adj [k] [I]) {lowcost [I] = G-> adj [k] [I]; adj [I] = K ;}}cout <num <Endl ;}int main () {graph * g = new graph; Create (g ); prim (g); System ("pause ");}


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.