c语言写一个,最小生成树算法。
时间: 2024-03-28 08:14:58 浏览: 51
最小生成树有很多种生成方法,主要有普利姆算法和克鲁斯卡尔算法,通过C语言easyx图形库实现
5星 · 资源好评率100%
好的,以下是使用C语言编写的最小生成树算法:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTICES 1000
#define INF 1000000
typedef struct {
int start;
int end;
int weight;
} Edge;
int num_vertices;
int graph[MAX_VERTICES][MAX_VERTICES];
bool visited[MAX_VERTICES];
int prim() {
int sum_weight = 0;
int count_vertices = 1;
visited[0] = true;
while (count_vertices < num_vertices) {
int min_weight = INF;
int min_start = -1;
int min_end = -1;
for (int i = 0; i < num_vertices; i++) {
if (visited[i]) {
for (int j = 0; j < num_vertices; j++) {
if (!visited[j] && graph[i][j] < min_weight) {
min_weight = graph[i][j];
min_start = i;
min_end = j;
}
}
}
}
if (min_start != -1 && min_end != -1) {
visited[min_end] = true;
count_vertices++;
sum_weight += min_weight;
}
}
return sum_weight;
}
int main() {
int num_edges;
scanf("%d %d", &num_vertices, &num_edges);
for (int i = 0; i < num_vertices; i++) {
for (int j = 0; j < num_vertices; j++) {
graph[i][j] = INF;
}
}
for (int i = 0; i < num_edges; i++) {
int start, end, weight;
scanf("%d %d %d", &start, &end, &weight);
graph[start][end] = weight;
graph[end][start] = weight;
}
int min_weight = prim();
printf("%d", min_weight);
return 0;
}
```
希望这可以帮到你!现在,请问你想聊些什么呢?
阅读全文