#include<iostream>
#include<cstring>
using namespace std;
int n,e;
char map[50][50];
char str[50];
void Prim()
{
int i,j,k;
int a[50],b[50];
int min;
for(i=0;i<n;i++)
{
a[i] = map[0][i];
b[i] = 0;
}
for(i=1;i<n;i++)
{
min = 101;
for(j=0;j<n;j++)
{
if(a[j]!=0 && a[j]<min)
{
min = a[j];
k = j;
}
}
cout<<"("<<str[b[k]]<<","<<str[k]<<")";
a[k] = 0;
for(j=0;j<n;j++)
{
if(map[k][j]!=0 && map[k][j]<a[j])
{
a[j] = map[k][j];
b[j] = k;
}
}
}
}
int main()
{
int i,j;
cin>>n>>e>>str;
memset(map,101,sizeof(map));
for(i=0;i<n;i++)
map[i][i] = 0;
for(i=0;i<e;i++)
{
char l,r;
int num;
cin>>l>>r>>num;
int t1 = 0,t2 = 0;
for(j=0;j<n;j++)
{
if(l == str[j]) t1 = j;
if(r == str[j]) t2 = j;
}
map[t1][t2] = num;
map[t2][t1] = num;
}
Prim();
return 0;
}
SWUST数据结构--求最小生成树(Prim算法)
最新推荐文章于 2024-02-15 20:50:29 发布