Prim最小生成树

典型例题HDU 1233

#include<bits/stdc++.h>
using namespace std;

const int INF=0x3f3f3f3f;
const int maxn=110;
bool vis[maxn];
int lowc[maxn];
int cost[maxn][maxn];

int Prim(int n)
{
int ans=0;
memset(vis,false,sizeof(vis));
vis[0]=true;
for(int i=1;i<n;i++)
{
lowc[i]=cost[0][i];
}
for(int i=1;i<n;i++)
{
int minc=INF;
int p=-1;
for(int j=0;j<n;j++)
{
if(!vis[j]&&minc>lowc[j])
{
minc=lowc[j];
p=j;
}
}
if(minc==INF)
{
return -1;
}
ans+=minc;
vis[p]=true;
for(int j=0;j<n;j++)
{
if(!vis[j]&&lowc[j]>cost[p][j])
{
lowc[j]=cost[p][j];
}
}
}
return ans;
}

int main()
{
ios::sync_with_stdio(false);
int n,a,b,w;
while(cin>>n)
{
if(!n)
break;
memset(cost,INF,sizeof(cost));
for(int i=0;i<n*(n-1)/2;i++)
{
cin>>a>>b>>w;
cost[a-1][b-1]=w;
cost[b-1][a-1]=w;

}
cout<<Prim(n)<<endl;
}
return 0;
}

//////////////////////////////////////////////

Prim的具体的思路是先选取一个点作为连通子网,在选择连通子网到其余点的距离最小的点构成连通子网并更新其余点到连通子网的最短距离,直到连通子网加入了n个点为止。

原文地址:https://www.cnblogs.com/Numblzw/p/9971897.html