hdu-1233 还是畅通工程---MST模板

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1233

题目大意:

求MST最小生成树

解题思路:

Prim算法直接套即可

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 100 + 10;
 5 const int INF = 1e9 + 7;
 6 int Map[maxn][maxn];
 7 int lowcost[maxn], mst[maxn];
 8 int n, m;
 9 void prim(int u)
10 {
11     ll ans = 0;
12     for(int i = 1; i <= n; i++)
13     {
14         lowcost[i] = Map[u][i];
15         mst[i] = u;
16     }
17     mst[u] = -1;
18     for(int i = 1; i <= n; i++)
19     {
20         int minn = INF;
21         int v = -1;
22         //寻找lowcost数组里面的未加入mst的最小值
23         for(int j = 1; j <= n; j++)
24         {
25             if(mst[j] != -1 && lowcost[j] < minn)
26             {
27                 v = j;
28                 minn = lowcost[j];
29             }
30         }
31         if(v != -1)
32         {
33             mst[v] = -1;
34             ans += lowcost[v];
35             for(int j = 1; j <= n; j++)
36             {
37                 if(mst[j] != -1 && lowcost[j] > Map[v][j])
38                 {
39                     lowcost[j] = Map[v][j];
40                     mst[j] = v;
41                 }
42             }
43         }
44     }
45     printf("%lld\n", ans);
46 }
47 int main()
48 {
49     while(scanf("%d", &n) != EOF && n)
50     {
51         m = n * (n - 1) / 2;
52         int u, v, w;
53         memset(Map, 0, sizeof(Map));
54         memset(lowcost, 0, sizeof(lowcost));
55         while(m--)
56         {
57             scanf("%d%d%d", &u, &v, &w);
58             Map[u][v] = Map[v][u] = w;
59         }
60         prim(1);
61     }
62     return 0;
63 }

 

posted @ 2018-04-21 10:42  _努力努力再努力x  阅读(120)  评论(0编辑  收藏  举报