# 求最小生成树(Prim算法）

#include< iostream>
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)

//完成Prim算法

int main()

Graph my;
int n,e;
cin>>n>>e;
create(my,n,e);
Prim(my,0);
return 0;

#### 样例输入

6
10
ABCDEF
A B 6
A C 1
A D 5
B C 5
C D 5
B E 3
E C 6
C F 4
F D 2
E F 6

#### 样例输出

(A,C)(C,F)(F,D)(C,B)(B,E)
#include<iostream>
using namespace std;

typedef struct
{
int n;
int e;
char data[500];
int edge[500][500];
}Graph;
void create(Graph &G, int n, int e)
{
int i, j, k, w;
char a, b;
for (i = 1; i <= n; i++)
cin >> G.data[i];
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
G.edge[i][j] = 100;

for (k = 0; k< e; k++)
{
cin >> a;
cin >> b;
cin >> w;
for (i = 1; i <= n; i++)
if (G.data[i] == a) break;
for (j = 1; 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 printEdge(Graph &G)
{
for (int i = 1; i <= G.n; i++)
{
for (int j = 1; j <= G.n; j++)
{
cout << G.edge[i][j] << " ";
}
cout << endl;
}
}
void print(int a[][2], int n)
{
for (int i = 1; i <= n; i++)
cout << a[i][0] << " " << a[i][1] << endl;
cout << endl;
}
void Prim(Graph &G, int k)
{
//完成Prim算法
int visit[100] = { 0 }, t = G.n - 1;
visit[k] = 1;
int ass[100][2], min = 1;
for (int i = 1; i <= G.n; i++)
{
ass[i][0] = k;
ass[i][1] = G.edge[1][i];
if (ass[min][1] > ass[i][1])
min = i;
}
while (t--)
{
int now = min;
min = 1;
cout << "(" << G.data[ass[now][0]] << "," << G.data[now] << ")";
visit[now] = 1;
ass[now][1] = 100;
for (int i = 1; i <= G.n; i++)
{
//替换对应最短的
if (visit[i])
continue;
if (ass[i][1] > G.edge[now][i])
{
ass[i][0] = now;
ass[i][1] = G.edge[now][i];
}
}
for (int i = 1; i <= G.n; i++)
if (ass[min][1] > ass[i][1])
min = i;
}
}

int main()
{
Graph my;
int n, e;
cin >> n >> e;
create(my, n, e);
Prim(my, 1);
return 0;
}