王道考研 ++++ 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章