//
//Description:最小生成树算法
//
#include <iostream>
using namespace std;
#define max 20 //---
#define num 6 //结点的个数
float array[num + 1][num + 1];
void prim(float c[num + 1][num + 1])
{
float lowcost[num + 1];
int closest[num + 1];
bool s[num + 1];
s[1] = true;
for (int i = 2; i <= num; i++)
{
lowcost[i] = c[1][i];
closest[i] = 1;
s[i] = false;
}
for (int i = 1; i<num; i++)
{
float min = max;//---
int j = 1;
for (int k = 2; k <= num; k++)
if ((lowcost[k]<min) && (!s[k]))
{
min = lowcost[k];
j = k;
}
cout << "结点 " << j << " ,其近临结点为 " << closest[j] << endl;
s[j] = true;
for (int k = 2; k <= num; k++)
{
if ((c[j][k]<lowcost[k]) && (!s[k]))
lowcost[k] = c[j][k];
closest[k] = j;
}
}
}
void intput()
{
for (int i = 1; i <= num; i++)
{
for (int j = i + 1; j <= num; j++)
{
cout << "请输入 c[" << i << "][" << j << "] 的值" << endl;
cin >> array[i][j];
array[j][i] = array[i][j];
}
cout << endl;
}
}
void output()
{
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= num; j++)
{
cout << array[i][j] << '\t';
}
cout << endl;
}
}
void main()
{
intput();
output();
prim(array);
}
最小生成树Prim算法(贪心算法)
最新推荐文章于 2024-09-04 16:21:12 发布