最小生成树——稠密图——prim算法

 1 #include <algorithm>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 const int N = 505, INF = 0x3f3f3f3f;
 9 int n, m;
10 int g[N][N]; //邻接矩阵,储存所有边
11 int dist[N]; //储存其他点到当前最小生成树这个集合的距离
12 bool st[N];  //储存每个点是否在最小生成树中
13 
14 int prim()
15 {
16     int ans = 0;
17     for (int i = 0; i < n; i ++ )
18     {
19         int t = -1;
20         for (int j = 1; j <= n; j ++ )
21             if (!st[j] && (t == -1 || dist[j] < dist[t])) t = j;
22 
23         st[t] =true;
24 
25         if (i && dist[t] == INF) return INF;//如果是第一次更新那么dist数组就全都为0x3f3f3f3f,此时只是将1号点加进集合中
26         if (i) ans += dist[t];
27 
28         for (int j = 1; j <= n; j ++ )
29             dist[j] = min(dist[j], g[t][j]);
30     }
31 
32     return ans;
33 }
34 
35 int main()
36 {
37     memset(g, 0x3f, sizeof g);
38     memset(dist, 0x3f,sizeof dist);
39     cin >> n >> m;
40 
41     while (m -- )
42     {
43         int a, b, c;
44         cin >> a >> b >> c;
45         g[a][b] = g[b][a] = min(g[a][b], c);
46     }
47 
48     int ans = prim();
49 
50     if (ans == INF) puts("impossible");
51     else cout << ans << endl;
52     return 0;
53 }

dist数组储存的是图中所有的点到最小生成树的距离,由于一个点只能被加入一次那么加入之后这个点到生成树中的距离就可以看成是无穷大,而其他不在生成树中的距离就是生成树中的个点到不在生成树中的点的距离即

 此时dist数组的变化即为

Max 6   1   5   Max Max 
1   5   1   5   6   4 
1   5   1   2   6   4 
1   5   1   2   6   2 
1   5   1   2   3   2 
1   3   1   2   3   2 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值