#include<stdio.h>
int find(int, int parent[10]);
int uni(int, int, int parent[10]);
int main()
{
int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];
printf("\n\tImplementation of Kruskal's algorithm\n");
printf("\nEnter the no. of vertices:");
scanf("%d", &n);
printf("\nEnter the cost matrix:\n");
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("Enter the cost of the edge(%d,%d)=", i, j);
scanf("%d", &cost[i][j]);
if (cost[i][j] == 0)
{
cost[i][j] = 999;
}
}
}
printf("The edges of Minimum Cost Spanning Tree are\n");
while (ne < n)
{
for (i = 1, min = 999; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (cost[i][j] < min)
{
min = cost[i][j];
a = u = i;
b = v = j;
}
}
}
u = find(u, parent);
v = find(v, parent);
if (uni(u, v, parent) == 1)
{
printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
mincost += min;
}
cost[a][b] = cost[b][a] = 999;
}
printf("\n\tMinimum cost = %d\n", mincost);
}
int uni(int i, int j, int parent[10])
{
if (i != j)
{
parent[j] = i;
return 1;
}
return 0;
}
int find(int i, int parent[10])
{
while (parent[i])
{
i = parent[i];
}
return i;
}
這是無法計算U,V,單...我能夠進入值,但我得到一個消息分段錯誤(核心轉儲)。我猜有一些問題,函數find和uni(可能在傳遞數組父項)..分段故障核心轉儲在Kruskal算法
你知道哪裏有錯誤發生? – 2015-02-06 10:20:41
就是這樣,就你而言?沒有運行調試器,甚至沒有添加printf()來檢查發生了什麼,或者在哪個*特定的值下程序失敗?沒有檢查'scanf()的返回值,沒有鏡像程序讀取的內容?沒有'assert()'? – DevSolar 2015-02-06 10:21:56
所有未檢查scanf結果的代碼都應該通過計算器自動拒絕併發送相應的消息。 :-) – Jens 2015-02-06 10:34:11