#include <stdio.h>
#include <string.h>
#define INF 0x3f3f3f3f
#define N 300
int map[N][N];
int prim(int vertex, int root) {
int low[vertex + 1];
bool vis[vertex + 1];
int i, j, k, tmp, ans = 0;
memset(vis, false, sizeof(vis));
for (i = 1; i <= vertex; i++)
low[i] = map[1][i];
vis[root] = true;
for (i = 1; i < vertex; i++) {
tmp = INF;
for (j = 1; j <= vertex; j++)
if (!vis[j] && low[j] < tmp)
tmp = low[k = j];
vis[k] = true;
ans += tmp;
for (j = 1; j <= vertex; j++)
if (!vis[j] && map[k][j] < low[j])
low[j] = map[k][j];
}
return ans;
}
int main() {
int vertex, edge, u, v, value, i;
scanf("%d%d", &vertex, &edge);
memset(map, INF, sizeof(map));
for (i = 0; i < edge; i++) {
scanf("%d%d%d", &u, &v, &value);
if (value < map[u][v])
map[u][v] = map[v][u] = value;
}
printf("%d\n", prim(vertex, 1));
return 0;
}
Prim 算法
最新推荐文章于 2024-09-04 16:21:12 发布