【发布时间】:2017-07-04 17:57:05
【问题描述】:
我正在尝试实现 Kruskal 算法。这是我正在使用的结构图:
g =边的数组,它保持左端和右端以及边的权重;
c = 存储 conex 组件的数组; c[N] = 我们找到第 N 个顶点的 conex 分量;
a = 存储 MST 的数组;
m = nr 个顶点;
n = nr 个节点。
下面的代码有两个问题:
1) 对于以下输入,它输出 MST 的成本是 18(这是错误的,成本实际上是 14):
7 ( =m)
6 (=n)
1 2 9
1 3 5
1 4 2
2 3 7
3 5 3
4 6 1
5 6 1
2) 逐步编译代码不会出现任何错误,虽然程序的实际执行有时会停止,但我认为是在打印 MST 的成本时。
感谢您的帮助!代码如下:
#include<stdio.h>
#include<stdlib.h>
#define grafMAX 101
FILE *fin = fopen("grafin.txt","r");
FILE *fout = fopen("grafout.txt","w");
struct Vertex{
int first,last,Cost;
};
void read_graf(Vertex **g, int *c, int &m, int &n){
int x,y,w;
fscanf(fin,"%d%d",&m,&n);
*g = (Vertex *)malloc(m*sizeof(Vertex));
for(int i=1;i<=m;++i){
fscanf(fin,"%d%d%d",&x,&y,&w);
(*g+i)->first = x;
(*g+i)->last = y;
(*g+i)->Cost = w;
}
for(int i=1;i<=n;++i)
c[i] = i;
}
int costMST(Vertex *g, int *a, int n){
int MST = 0;
for(int i=1;i<n;++i)
MST += g[a[i]].Cost;
return MST;
}
void Kruskal(Vertex *g, int *c, int *a, int n){
int nr = 0, mini, maxi;
for(int i=1;nr<n-1;++i)
if(c[g[i].first] != c[g[i].last]){
a[++nr] = i;
if(c[g[i].first] < c[g[i].last]){
mini = c[g[i].first];
maxi = c[g[i].last];
}
else{
maxi = c[g[i].first];
mini = c[g[i].last];
}
for(int j=1;j<=n;++j)
if(c[j] == maxi)
c[j] = mini;
}
}
inline int cmp(const void *a, const void *b){
return (((Vertex *)a)->Cost - ((Vertex *)b)->Cost);
}
int a[grafMAX], c[grafMAX];
int main(){
Vertex *g;
int m, n;
read_graf(&g,c,m,n);
qsort(g,m,sizeof(Vertex),cmp);
Kruskal(g,c,a,n);
fprintf(fout,"The cost of the MST is: %d.\n",costMST(g,a,n));
fclose(fin);
fclose(fout);
return 0;
}
【问题讨论】:
标签: c++ algorithm quicksort minimum-spanning-tree kruskals-algorithm