我没有太多使用矩阵的经验。我如何让我的矩阵与用户输入一起工作,它对我有用的唯一方法是使用#define N 5。否则我会收到错误消息。还有一种简单的方法可以从输入文件制作矩阵吗?输入文件看起来像这样:
第一个数字告诉程序有多少个顶点,接下来的数字就像 v0 到 v1 一样,权重为 6,依此类推。我的 Kruskal 方法有效我创建了一个分区类来帮助使用 Kruskal 算法,只是无法真正计算出矩阵。
4
0 1 6
0 3 4
1 2 2
2 4 9
3 4 7
#include <iostream>
using namespace std;
//int X = 5;
#define N 5
Partition p;
// Finds MST using Kruskal's algorithm
void kruskalMST(int cost[][N])
{
int mincost = 0; // Cost of min MST.
// Initialize sets of disjoint sets.
//for (int i = 0; i < V; i++)
// parent[i] = i;
// Include minimum weight edges one by one
int edge_count = 0;
while (edge_count < N - 1) {
int min = INT_MAX, a = -1, b = -1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (p.uf_find(i) != p.uf_find(j)
&& cost[i][j] < min) {
min = cost[i][j];
a = i;
b = j;
}
}
}
p.uf_union(a, b);
printf("Edge %d:(%d, %d) cost:%d \n",
edge_count++, a, b, min);
mincost += min;
}
printf("\n Minimum cost= %d \n", mincost);
}
// driver program to test above function
int main()
{
int X;
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
ifstream infile;
string infile_name, outfile_name;
cout << "Please enter an input file with equations: ";
cin >> infile_name;
infile.open(infile_name.c_str());
int cost[][N] = {
{ INT_MAX, 2, INT_MAX, 6, INT_MAX },
{ 2, INT_MAX, 3, 8, 5 },
{ INT_MAX, 3, INT_MAX, INT_MAX, 7 },
{ 6, 8, INT_MAX, INT_MAX, 9 },
{ INT_MAX, 5, 7, 9, INT_MAX },
};
// Print the solution
kruskalMST(cost);
return 0;
}