普里姆算法

#include<stdio.h>
#include<stdlib.h>
#define INFINITY INT_MAX
#define MAX_VERTEX_NUM 20
typedef enum {DG,DN,UDG,UDN}GraphKind;
typedef enum {ERROR,OK}Status;
typedef int VRType;
typedef int VertexType;
typedef struct ArcCell{
    VRType adj;
}ArcCell, AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct {
    VertexType vexs[MAX_VERTEX_NUM];
    AdjMatrix arcs;
    int vexnum, arcnum;
    GraphKind kind;
}MGraph;
struct dge{
    VertexType adjvex;
    VRType lowcost;
}closedge[MAX_VERTEX_NUM];
VertexType LocateVex(MGraph G, VertexType u) {
    return u - 1;
}
//void MiniSpanTree_PRIM(MGraph G, VertexType u);
Status CreateUND(MGraph &G) {
    printf("enter vexnum,arcnum:\n");
    scanf("%d,%d", &G.vexnum, &G.arcnum);
    printf("enter vexs:\n");
    for (int i = 0; i < G.vexnum; i++) scanf("%d", &G.vexs[i]);
    for (int i = 0; i < G.vexnum; i++)
        for (int j = 0; j < G.vexnum; j++) G.arcs[i][j] = { INFINITY };
    for (int i = 0; i < G.vexnum; i++)
        for (int j = 0; j < G.vexnum; j++)G.arcs[i][j].adj = INFINITY;
    printf("enter arcs:v1,v2,w:\n");
    for (int k = 0; k < G.arcnum; k++) {
        VertexType v1, v2;
        VRType w;
        scanf("%d,%d,%d", &v1, &v2, &w);
        int i = LocateVex(G, v1);
        int j = LocateVex(G, v2);
        G.arcs[i][j].adj = G.arcs[j][i].adj = w;
    }
    return OK;
}

int minmum(MGraph G,int k) {
    int t = INFINITY , loc = 0;                       //???
    for (int i = 0; i < G.vexnum; i++) {
        if (i != k&&closedge[i].lowcost > 0 && closedge[i].lowcost < t) {
            t = closedge[i].lowcost;
            loc = i;
        }
    }
    return loc;
}

void MiniSpanTree_PRIM(MGraph G, VertexType u){
    int k = LocateVex(G,u);
    for (int j = 0; j < G.vexnum; j++) {
        if (j != k)closedge[j] = { u,G.arcs[k][j].adj };//???
    }
    closedge[k].lowcost = 0;
    for (int i = 1; i < G.vexnum; i++) {
        k = minmum(G,k);
        printf("%d->%d\n", closedge[k].adjvex, G.vexs[k]);
        closedge[k].lowcost = 0;
        for (int j = 0; j < G.vexnum; j++)
            if (G.arcs[k][j].adj < closedge[j].lowcost)
                closedge[j] = { G.vexs[k],G.arcs[k][j].adj };
    }
}
int main()
{
    MGraph G;
    CreateUND(G);
    MiniSpanTree_PRIM(G,1);
    return 0;
}

这里写图片描述

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐