#include<iostream>
using namespace std;
const int inf = 0x3f3f3f3f;
int dist[110][110] = { 0 }, N = 0;
int prim()
{
int s = 1; //源点(最初的源点为1)
int m = 1; //记录最小生成树的顶点数
bool u[110]; //记录某顶点是否属于最小生成树
int w = 0; //最小生成树的总权值
int minlength = 0; //每个新源点到其它点的最短路
int flag_point;
int low_dis[110]; //各个源点s到其它点的最短路
memset(low_dis, inf, sizeof(low_dis));
memset(u, false, sizeof(u));
u[s] = true;
while (1)
{
if (m == N) //当最小生成树的顶点数等于原图的顶点数时,说明最小生成树查找完毕
break;
w = inf;
for (int j = 2; j <= N; j++)
{
if (!u[j] && low_dis[j]>dist[s][j])
low_dis[j] = dist[s][j];
if (!u[j] && w>low_dis[j])
{
w = low_dis[j];
flag_point = j; //记录最小权边中不属于最小生成树的点j
}
}
s = flag_point; //顶点j与旧源点合并
u[s] = true; //j点并入最小生成树(相当于从图上删除j点,让新源点接替所有j点具备的特征)
minlength += w; //当前最小生成树的总权值
m++;
}
return minlength;
}
int main()
{
int i = 0, j = 0;
while (cin>>N)
{
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
cin >> dist[i][j];
}
}
cout << prim() << endl;
}
return 0;
}
poj 1258 prim最小生成树
最新推荐文章于 2022-03-09 16:55:41 发布