kruskal算法(C++实现)

template<class T> bool Kruskal(EdgeNode<T> t[]) { //如果不连通则返回false //如果连通,则在t[0->n-2]中返回最小生成树 int n = Vertices(); int e = Edges(); InitializePos(); EdgeNode<T> *E = new EdgeNode<T> [e+1]; int k = 0; //把边都放到数组E for (int i = 1; i <= n; i++) { int j; T c; First(i, j, c); while (j) { if (i < j) { E[++k].weight = c; E[k].u = i; E[k].v = j; } Next(i, j, c); } } //把边放到最小堆 MinHeap<EdgeNode<T> > H(1); H.Initialize(E, e, e); UnionFind U(n); k = 0; while (e && k < n - 1) { EdgeNode<T> x; H.DeleteMin(x); //获得最小消耗边 e--; int a = U.Find(x.u); int b = U.Find(x.v); //是否构成环 if (a != b) { //不构成环,ok t[k++] = x; U.Union(a,b); } } DeactivatePos(); H.Deactivate(); return (k == n - 1); } template<class T> bool Kruskal(EdgeNode<T> t[]) { //如果不连通则返回false //如果连通,则在t[0->n-2]中返回最小生成树 int n = Vertices(); int e = Edges(); InitializePos(); EdgeNode<T> *E = new EdgeNode<T> [e+1]; int k = 0; //把边都放到数组E for (int i = 1; i <= n; i++) { int j; T c; First(i, j, c); while (j) { if (i < j) { E[++k].weight = c; E[k].u = i; E[k].v = j; } Next(i, j, c); } } //把边放到最小堆 MinHeap<EdgeNode<T> > H(1); H.Initialize(E, e, e); UnionFind U(n); k = 0; while (e && k < n - 1) { EdgeNode<T> x; H.DeleteMin(x); //获得最小消耗边 e--; int a = U.Find(x.u); int b = U.Find(x.v); //是否构成环 if (a != b) { //不构成环,ok t[k++] = x; U.Union(a,b); } } DeactivatePos(); H.Deactivate(); return (k == n - 1); } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kongbu0622/archive/2009/10/09/4647463.aspx

你可能感兴趣的:(kruskal算法(C++实现))