#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
#define INFINITY 0x7fffffff
typedef struct
{
int U[MAX][MAX];
char adj[MAX][10];
int vexnum, arcnum;
}Graph;
typedef struct
{
char temp_adj[MAX];
int temp_weight;
}Closedge;
void Creat(Graph *G)
{
int i, weight;
char tail[10],head[10];
printf("请输入顶点个数:");
scanf("%d", &G->vexnum);
printf("请输入弧的个数:");
scanf("%d", &G->arcnum);
printf("请输入每个顶点:");
fflush(stdin);
for (i = 0; i < G->vexnum; i++)
for (int j = 0; j < G->vexnum; j++)
{
G->U[i][j] = INFINITY;
}
for (i = 0; i < G->vexnum; i++)
scanf("%s", G->adj[i]);
printf("请输入图:");
for (i = 0; i < G->arcnum; i++)
{
scanf("%s%s%d", tail,head,&weight);
for (int j = 0; j < G->vexnum; j++)
{
if (!strcmp(G->adj[j], tail))
for (int k = 0; k < G->vexnum; k++)
if (!strcmp(G->adj[k], head))
{
G->U[j][k] = weight;
G->U[k][j] = weight;
break;
}
}
}
/*for (i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
printf("%d\n", G->U[i][j]);*/
}
void MiniSpanTree_PRIM(Graph *G)
{
Closedge closedge[MAX];
int i, j, k,n=1;
int temp;
k = 0;
for (i = 1; i < G->vexnum; i++)
{
strcpy(closedge[i].temp_adj, G->adj[k]);
closedge[i].temp_weight = G->U[0][i];
}
closedge[0].temp_weight = 0;
for (i = 1; i < G->vexnum; i++)
{
temp = G->U[k][1];
for (j = 1; j < G->vexnum; j++)
{
if (temp > G->U[k][j])
{
temp = G->U[k][j];
n = j;
}
}
printf("%s---%s---%d\n", closedge[n].temp_adj,G->adj[n] , closedge[n].temp_weight);
G->U[k][n] = INFINITY;
G->U[n][k] = INFINITY;
k = n;
for (j = 1; j < G->arcnum; j++)
{
if (G->U[k][j] < closedge[j].temp_weight)
{
strcpy(closedge[j].temp_adj, G->adj[k]);
closedge[j].temp_weight = G->U[k][j];
}
}
}
}
int main()
{
Graph G;
Creat(&G);
MiniSpanTree_PRIM(&G);
system("pause");
return 0;
}
/*
a
s
3
a
d
6
s
d
8
*/