最小生成树——Kruskal算法

/*
1 4 12
2 3 17
0 5 19
2 5 25
3 5 25
4 5 26
0 1 34
3 4 38
0 2 46
*/
//Geeksun 2018.06.14
#include <iostream>
using namespace std;
const int maxSize = 10;

struct EdgeType
{
    int from,to;
    int weight;
};
struct EdgeGraph
{
    EdgeType edge[maxSize];
    int edgeNum,vertexNum;
};
int findRoot(int parent[],int v)
{
    int t = v;
    if(parent[t] == -1)
    {
        return t;
    }
    else
    {
        return findRoot(parent,parent[t]);
    }
}
void Kruskal(EdgeGraph G)
{
    int parent[maxSize];
    for(int i = 0;i < G.vertexNum;i++)
    {
        parent[i] = -1;
    }
    int num = 0;
    for(int i = 0;i < G.edgeNum;i++)
    {
        int vex1 = findRoot(parent,G.edge[i].from);
        int vex2 = findRoot(parent,G.edge[i].to);
        if(vex1 != vex2)
        {
            cout << "(" << G.edge[i].from << G.edge[i].to << ")" << endl;
            parent[vex2] = vex1;
            num++;
            if (num == G.vertexNum - 1) return;
        }
    }
}
int main()
{
    struct EdgeGraph G;
    G.vertexNum = 6;
    G.edgeNum = 9;
    for(int i = 0;i < G.edgeNum;i++)//此处的边集数组已按权值从小到大排序 可以用sort直接排序
    {
        int from,to,weight;
        cin >> from >> to >> weight;
		G.edge[i].from = from;
		G.edge[i].to = to;
		G.edge[i].weight = weight;
    }
    Kruskal(G);
    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页