解法:
总结起来,Prim算法的核心思想是从一个顶点开始,一步一步地选择与当前最小生成树相邻的且权值最小的边,直到覆盖所有的顶点,形成一个最小生成树。
#include<iostream>
#include<vector>
using namespace std;
typedef struct
{
int n;
int e;
char data[500];
int edge[500][500];
}Graph;
typedef struct
{
int index;
int cost;
}mincost;
typedef struct
{
int x;
int y;
int weight;
}EDGE;
typedef struct
{
int index;
int flag;
}F;
void create(Graph& G, int n, int e)
{
int i, j, k, w;
char a, b;
for (i = 0; i < n; i++)
cin >> G.data[i];
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
if (i == j)
G.edge[i][j] = 0;
else
G.edge[i][j] = 100;
}
for (k = 0; k < e; k++)
{
cin >> a;
cin >> b;
cin >> w;
for (i = 0; i < n; i++)
if (G.data[i] == a) break;
for (j = 0; j < n; j++)
if (G.data[j] == b) break;
G.edge[i][j] = w;
G.edge[j][i] = w;
}
G.n = n;
G.e = e;
}
void Prim(Graph& G, int k)
{
vector<mincost> closed(G.n);
closed[k] = { -1,0 };
for (int i = 0; i < G.n; i++) {
if (i != k) {
closed[i] = { k,G.edge[k][i] };
}
}
for (int i = 1; i < G.n; i++) {
mincost t = { 0,100 };
for (int j = 0; j < G.n; j++) {
if (closed[j].index!=-1&&closed[j].cost!=100)
if (t.cost > closed[j].cost) {
t.index = j;
t.cost = closed[j].cost;
}
}
char a = G.data[closed[t.index].index];
char b = G.data[t.index];
cout << '(' << a << ',' << b << ')';
closed[t.index] = { -1,0 };
for (int m = 0; m < G.n; m++) {
if (closed[m].cost > G.edge[t.index][m])
closed[m] = { t.index,G.edge[t.index][m] };
}
}
}
int main()
{
Graph my;
int n, e;
cin >> n >> e;
create(my, n, e);
Prim(my, 0);
return 0;
}