Graph structure exercise-Minimum Spanning Tree

Source: Internet
Author: User
Graph structure exercise-Minimum Spanning Tree Time Limit: 1000 ms memory limit: 65536 k any questions? Click Here ^_^ 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 11 0
Sample output
20
Prompt Source: Zhao liqiang sample program

# Include <stdio. h> # include <string. h> # include <stdlib. h> # define INF 999999int map [110] [110]; int vis [110]; int dis [110]; int sum; void prim (int n) {int I, j, k; int min; sum = 0; memset (VIS, 0, sizeof (VIS); for (I = 1; I <= N; I ++) dis [I] = map [1] [I]; vis [1] = 1; for (I = 2; I <= N; I ++) {min = inf; for (j = 1; j <= N; j ++) {If (min> dis [J] &! Vis [J]) {k = J; min = dis [J] ;}} vis [k] = 1; sum + = min; For (j = 1; j <= N; j ++) {If (Map [k] [J] <dis [J] &! Vis [J]) dis [J] = map [k] [J] ;}} printf ("% d \ n", sum);} int main () {int n, m, I, j; int U, V, W; while (~ Scanf ("% d", & N, & M) {If (M <n-1) {printf ("0 \ n ");} else {for (I = 1; I <= N; I ++) for (j = 1; j <= N; j ++) {if (I = J) map [I] [J] = 0; else map [I] [J] = inf;} while (M --) {scanf ("% d ", & U, & V, & W); If (W <map [u] [v]) // this step is used to prevent, 3 In this case, map [u] [v] = map [v] [u] = W;} prim (n) ;}} return 0 ;}

Zookeeper

Graph structure exercise-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.