图-普利姆算法

普利姆算法

#include 

using namespace std;

typedef char VerTexType;
typedef int ArcType;
#define MVNum 100
#define MaxInt 32767

struct {
    VerTexType adjvex;
    ArcType lowcost;
}closedeg[MVNum];

typedef char VerTexType;
typedef int ArcType;
typedef struct {
    VerTexType vexs[MVNum];
    ArcType arcs[MVNum][MVNum];
    int vexnum, arcnum;
}AMGraph;

int LocateVex(AMGraph G, VerTexType v) {
    for (int i = 0;i < G.vexnum;++i) {
        if (G.vexs[i] == v)
            return i;
    }
    return -1;
}

void CreateUDN(AMGraph& G) {
    int i, j, k;
    cout << "请输入总顶点数,总边数,以空格隔开:";
    cin >> G.vexnum >> G.arcnum;
    cout << endl;

    cout << "输入点的名称,如a" << endl;

    for (i = 0;i < G.vexnum;++i) {
        cout << "请输入第" << (i + 1) << "个点的名称:";
        cin >> G.vexs[i];
    }
    cout << endl;

    for (i = 0;i < G.vexnum;i++) {
        for (j = 0;j < G.vexnum;++j) {
            G.arcs[i][j] == MaxInt;
        }
    }
    cout << "输入边依附的顶点及权值,如a b 5"<> v1 >> v2 >> w;
        i = LocateVex(G, v1);
        j = LocateVex(G, v2);
        G.arcs[i][j] = w;
        G.arcs[j][i] = G.arcs[i][j];
    }
}

int Min(AMGraph G) {
    int i;
    int index = -1;
    int min = MaxInt;
    for (i = 0;i < G.vexnum;++i) {
        if (min > closedeg[i].lowcost&& closedeg[i].lowcost != 0) {
            min = closedeg[i].lowcost;
            index = i;
        }
    }
    return index;
}

void MinSpanTree_Prim(AMGraph G, VerTexType u) {
    int i, j, k;
    VerTexType u0, v0;
    k = LocateVex(G, u);
    for (j = 0;j < G.vexnum;++j) {
        if (j != k) {
            closedeg[j].adjvex = u;
            closedeg[j].lowcost = G.arcs[k][j];
        }
    }
    closedeg[k].lowcost = 0;
    for (i = 1;i < G.vexnum;++i) {
        k = Min(G);
        u0 = closedeg[k].adjvex;
        v0 = G.vexs[k];
        cout << "边  " << "--->" << v0 << endl;
        closedeg[k].lowcost = 0;
        for (j = 0;j < G.vexnum;++j) {
            if (G.arcs[k][j] < closedeg[j].lowcost) {
                closedeg[j].adjvex = G.vexs[k];
                closedeg[j].lowcost = G.arcs[k][j];
            }
        }
    }
}

int main() {
    cout << "普里姆算法" << endl;
    AMGraph G;
    CreateUDN(G);
    cout << endl;
    cout << "无向图G创建完成!" << endl;

    cout << "利用普里姆算法构造最小生成树结果:" <

你可能感兴趣的:(图-普利姆算法)