最小生成树——稠密图——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

浙公网安备 33010602011771号