#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//該結構體用來表示從某個頂點可以到達的其他頂點
struct ENode
{
int secPoint;//頂點號
int weight;
ENode *next;//指向下一個頂點的指標
};
//該結構體表示每一個頂點的資訊
struct PNode
{
char value;//頂點的值
ENode *next;//指向頂點可以到達的其他第一個頂點的指標
};
//圖的結構體,該圖最多有100個頂點
struct Map
{
PNode point[100];//數組的下標就是這個頂點的頂點號
int numPoint,numEdge;
};
//建圖的函數
struct Map *CreateMap()
{
struct Map *mp = (struct Map*)malloc(sizeof(struct Map));
int i,j;
int firP,secP,weight;
int numP,numE;
char infoP;
memset(mp,0,sizeof(struct Map));
printf("請輸入頂點數和邊數,格式為‘頂點數,邊數’:\n");
scanf("%d,%d",&numP,&numE);
mp->numPoint = numP;
mp->numEdge = numE;
printf("請輸入各個頂點的資訊,沒有分隔字元的連續輸入:\n");
fflush(stdin);
for(i=0;i<mp->numPoint;i++)
{
scanf("%c",&infoP);
mp->point[i].value = infoP;
}
printf("請輸入邊和權重,格式為‘頂點-頂點,權重’\n");
fflush(stdin);
for(j=0;j<mp->numEdge;j++)
{
scanf("%d-%d,%d",&firP,&secP,&weight);
struct ENode *newNode = (struct ENode *)malloc(sizeof(struct ENode));
newNode->secPoint = secP;
newNode->weight=weight;
newNode->next = mp->point[firP].next;
mp->point[firP].next = newNode;
}
return mp;
}
void Prim(struct Map *mp)
{
int pointArray[20],i,j,min;
int curPoint1,curPoint2;
struct ENode *pNode;
memset(pointArray,0,sizeof(pointArray));
pointArray[0]=1;
i=1;
printf("\n\n最小產生樹的各個邊:\n");
//有頂點還未加入則迴圈
while(i<mp->numPoint)
{
min=65537;
//迴圈遍曆全圖的各個頂點
for(j=0;j<mp->numPoint;j++)
{
for(pNode=mp->point[j].next;pNode!=NULL;pNode=pNode->next)
{
//一個頂點已經找出另一個頂點還未找出並且權值小於當前的最小值則記錄下
if(pointArray[j]==0 && pointArray[pNode->secPoint]==1 && pNode->weight < min)
{
curPoint2=j;
curPoint1=pNode->secPoint;
min=pNode->weight;
}
else if(pointArray[j]==1 && pointArray[pNode->secPoint]==0 && pNode->weight < min)
{
curPoint1=j;
curPoint2=pNode->secPoint;
min=pNode->weight;
}
}
}
//一遍遍曆之後curPoint2就是這次找出的頂點
pointArray[curPoint2]=1;
i++;
printf("%d-%d\n",curPoint1,curPoint2);
}
}
int main()
{
struct Map *mp = CreateMap();
Prim(mp);
return 1;
}