最小生成树——prim算法

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

const int maxSize = 10;
const int maxNum = 99999;

struct shortEdge
{
    int adjvertex; //记录邻接点的下标
    int lowCost;   //权值
};
class MyGraph
{
public:
    void friend prim(MyGraph G);
    MyGraph(char vertex[],int vertexNum,int arcNum);
    ~MyGraph() {};
private:
    string vertex[maxSize];
    int arc[maxSize][maxSize];
    int arcNum,vertexNum;
};
MyGraph::MyGraph(char vertex[], int vertexNum, int arcNum)
{
    this->arcNum = arcNum;
    this->vertexNum = vertexNum;
    for(int i = 0; i < vertexNum; i++)
    {
        this->vertex[i] = vertex[i];
    }
    for(int i = 0; i < vertexNum; i++)
    {
        for(int j = 0; j < vertexNum; j++)
        {
            if(i == j)
            {
                arc[i][j] = 0;
            }
            else
            {
                arc[i][j] = maxNum;
            }
        }
    }
    for(int k = 0; k < arcNum; k++)
    {
        int i,j,weight;
        cin >> i >> j >> weight;
        arc[i][j] = weight;
        arc[j][i] = weight;
    }
}
int minEdge(struct shortEdge array[],int vertexNum)
{
    int k,min = 99999;
    for(int i = 0;i < vertexNum;i++)
    {
        if(array[i].lowCost < min&&array[i].lowCost != 0)
        {
            min = array[i].lowCost;
            k = i;
        }
    }
    return k;
}
void prim(MyGraph G)
{
    struct shortEdge array[maxSize];
    for(int i = 1; i < G.vertexNum; i++)
    {
        array[i].adjvertex = 0;
        array[i].lowCost = G.arc[0][i];
    }
    array[0].lowCost = 0;
    array[0].adjvertex = 0;
    for(int i = 1;i < G.vertexNum;i++)
    {
        int k;
        k = minEdge(array,G.vertexNum);
        cout << "(" << k << array[k].adjvertex << ")" << array[k].lowCost;
        array[k].lowCost = 0;
        for(int j = 1;j < G.vertexNum;j++)
        {
            if(G.arc[k][j] < array[j].lowCost)
            {
                array[j].lowCost = G.arc[k][j];   //此为待选边,不需要将权值置为0。
                array[j].adjvertex = k;
            }
        }
    }
}
int main()
{
    char vertex[7] = "012345";
    MyGraph myGraph(vertex,6,9);
    prim(myGraph);
    return 0;
}

阅读更多

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