Prim 算法原理及证明见提高课。
Prim算法求最小生成树 $O(n^{2})$,跟Dijkstra很像

完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
| #include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
int n, m;
int g[N][N];
int dist[N]; // 当前点距离集合的距离
bool st[N];
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0; // 最小生成树中所有边长度之和
for (int i = 0; i < n; i ++ ) // 每次找到集合外的,距集合距离最小的点
{
int t = -1; // t = -1 表示当前还没还有找到任何一个点
for (int j = 1; j <= n; j ++ )
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
// 当前图是不连通的,不存在最小生成树
if (i && dist[t] == INF) return INF;
if (i) res += dist[t]; // dist[t] 表示一条树边,加到生成树中去
for (int j = 1; j <= n; j ++ ) dist[j] = min(dist[j], g[t][j]);
st[t] = true;
}
return res;
}
int main()
{
scanf("%d%d", &n, &m);
memset(g, 0x3f, sizeof g);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = g[b][a] = min(g[a][b], c); // 无向图,处理重边
}
int t = prim();
if (t == INF) puts("impossible");
else printf("%d\n", t);
return 0;
}
|