采用邻接矩阵存储一个无向图,再用这个无向图的最小生成树的PRIM算法,这个代码需要从键盘读取数据,最后请给出他的一个测试数据
时间: 2024-02-18 13:01:44 浏览: 69
以下是一个使用邻接矩阵存储无向图并使用 Prim 算法求解最小生成树的 C++ 代码。此代码需要从键盘读取数据。
```c++
#include <iostream>
#include <climits> // For INT_MAX
using namespace std;
// Number of vertices in the graph
#define V 5
// A utility function to find the vertex with minimum key value,
// from the set of vertices not yet included in MST
int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
// A utility function to print the constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V])
{
cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << endl;
}
// Function to construct and print MST for a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
int parent[V]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge in cut
bool mstSet[V]; // To represent set of vertices not yet included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
// Always include first 0th vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent vertices of
// the picked vertex. Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
// print the constructed MST
printMST(parent, graph);
}
// Driver code
int main()
{
int graph[V][V];
// Read graph from keyboard
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
cin >> graph[i][j];
}
}
// Print the MST for the graph using Prim's algorithm
primMST(graph);
return 0;
}
```
以下是一个测试数据。请将以下数据复制到控制台中,并按顺序输入各个节点之间的边权值,然后按回车键。
```
0 2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
```
输出结果应为:
```
Edge Weight
0 - 1 2
1 - 2 3
0 - 3 6
1 - 4 5
```
阅读全文