王道考研 ++++ Prim 普里姆算法

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MaxSize 100
#define INF 1000001
typedef struct EageTable  //边表
{
  int eageNode,eageLen;           //节点 值
  struct EageTable *next; //指向下一条弧
}EageTable;
typedef struct HeadTable  //头表
{
  int headNode;           //值
  EageTable *first;       //指向头节点后第一个节点
}HeadTable,HeadList[MaxSize];
typedef struct{
  HeadList Graph;
  int headNum,arcNum;     //头节点书 弧数
}Graph;
bool vis[MaxSize] = {false};
int dis[MaxSize];

void InitGraph(Graph *G);
void CreateGraph(Graph *G,int flag,int a,int b,int len);
int Prim(Graph *G,int start);
/*初始化邻接表的头*/
void InitGraph(Graph *G)
{
  int i;
  for(i = 1;i <= G->headNum;i++)
  {
    G->Graph[i].headNode = i;
    G->Graph[i].first = NULL;
  }
}
/*创建邻接表*/
void CreateGraph(Graph *G,int flag,int a,int b,int len)
{
  EageTable* eage;
  eage = (EageTable*)malloc(sizeof(EageTable));
  eage->eageNode = b;
  eage->eageLen = len;
  //头插入
  eage->next = G->Graph[a].first;
  G->Graph[a].first = eage;
  //图为无向图时
  if(flag == 2)
  {
    EageTable* eagee;
    eagee = (EageTable*)malloc(sizeof(EageTable));
    eagee->eageNode = a;
    eagee->eageLen = len;
    //头插入
    eagee->next = G->Graph[b].first;
    G->Graph[b].first = eagee;
  }
}
/*prim*/
int Prim(Graph *G,int start)
{
  dis[start] = 0;//自己到自己为0
  int ans = 0;

  int i,j;
  for(i = 1;i <= G->headNum;i++)
  {
    int u = -1,min = INF;
    for(j = 1;j <= G->headNum;j++)//查找
    {
      if(dis[j] < min && !vis[j])
      {
        min = dis[j];
        u = j;
      }
    }

    if(u == -1)break;
    ans += dis[u];//累加 最小生成树的每一条边
    vis[u] = true;

    //遍历更新每个节点的最小值
    EageTable* eage = G->Graph[u].first;
    while (eage)
    {
      if(vis[eage->eageNode] == false && eage->eageLen < dis[eage->eageNode])
        dis[eage->eageNode] = eage->eageLen;
      eage = eage->next;
    }
  }
  return ans;
}
int main(int argc, char const *argv[]) {
  Graph G;
  int i,flag,start;

  memset(dis,INF,MaxSize * sizeof(int));
  printf("有向图输入1,无向图输入2:");
  scanf("%d",&flag);
  printf("请输入节点数:");
  scanf("%d",&G.headNum);
  InitGraph(&G);
  printf("请输入弧的条数(从1开始):");
  scanf("%d",&G.arcNum);
  printf("请输%d入条边:\n",G.arcNum);
  for(i = 0;i < G.arcNum;i++)
  {
    int a,b,len;
    scanf("%d %d %d",&a,&b,&len);
    CreateGraph(&G,flag,a,b,len);
  }
  printf("请输入起始点:");
  scanf("%d",&start);
  int ans = Prim(&G,start);
  printf("最小生成树路径长度是:");
  printf("%d\n",ans);
  return 0;
}
// 1 2 4
// 1 5 1
// 2 3 6
// 2 6 3
// 1 6 2
// 3 4 6
// 3 6 5
// 5 6 3
// 4 5 4
// 4 6 5

发布了85 篇原创文章 · 获赞 40 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/WX_1218639030/article/details/99292214