读入一个无向图的邻接矩阵,建立无向图并按照普里姆算法建立最后生成树,输出最小生成树和代价。 样例:输入4 0 2 4 0 2 0 3 5 4 3 0 1 0 5 1 0 输出6 用c语言实现代码
时间: 2024-02-23 09:02:21 浏览: 76
好的,以下是代码实现:
```
#include <stdio.h>
#include <limits.h>
#define MAX_VERTICES 100
int graph[MAX_VERTICES][MAX_VERTICES];
int parent[MAX_VERTICES];
int key[MAX_VERTICES];
int visited[MAX_VERTICES];
int minKey(int vertices)
{
int min = INT_MAX, min_index;
for (int v = 0; v < vertices; v++)
{
if (!visited[v] && key[v] < min)
{
min = key[v];
min_index = v;
}
}
return min_index;
}
int primMST(int vertices)
{
for (int i = 0; i < vertices; i++)
{
key[i] = INT_MAX;
visited[i] = 0;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < vertices - 1; count++)
{
int u = minKey(vertices);
visited[u] = 1;
for (int v = 0; v < vertices; v++)
{
if (graph[u][v] && !visited[v] && graph[u][v] < key[v])
{
parent[v] = u;
key[v] = graph[u][v];
}
}
}
int cost = 0;
for (int i = 1; i < vertices; i++)
cost += graph[i][parent[i]];
return cost;
}
int main()
{
int vertices;
scanf("%d", &vertices);
for (int i = 0; i < vertices; i++)
for (int j = 0; j < vertices; j++)
scanf("%d", &graph[i][j]);
int cost = primMST(vertices);
printf("最小生成树:\n");
for (int i = 1; i < vertices; i++)
printf("%d - %d\n", parent[i], i);
printf("代价: %d\n", cost);
return 0;
}
```
这段代码实现了普里姆算法,输入一个无向图的邻接矩阵,输出最小生成树和代价。
阅读全文