1.Prim算法
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
#define INF 0x3f3f3f3f
int mp[maxn][maxn];
int vis[maxn];
int dis[maxn];
int n,m;
int Prim()
{
for(int i=1;i<=n;i++)
{
vis[i]=0;
dis[i]=mp[1][i];
}
dis[1]=0;
vis[1]=1;
int ans=0;
for(int i=1;i<n;i++)
{
int minn= INF;
int idx=-1;
for(int j=1;j<=n;j++)
{
if(!vis[j]&&minn>dis[j])
{
minn=dis[j];
idx=j;
}
}
//int ans=0;
if(idx==-1)
return INF;//无最小生成树
ans+=minn;
vis[idx]=1;
for(int j=1;j<=n;j++)
{
if(!vis[j]&&dis[j]>mp[idx][j])
{
dis[j]=mp[idx][j];
}
}
}
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)==2&&n&&m)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)
mp[i][j]=0;
else
mp[i][j]=INF;
}
}
for(int i=0;i<m;i++)
{
int a,b,c;
cin>>a>>b>>c;
mp[a][b]=mp[b][a]=c;
}
int ans=Prim();
cout<<ans<<endl;
}
return 0;
}
2,Kruskal算法
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
#define INF 0x3f3f3f3f
struct Edge{
int be,en,dis;
bool operator<(const Edge&a)const{
return dis<a.dis;
}
}edge[maxn];
int n,m;
int F[maxn];
int Find(int idx)
{
//cout<<F[idx]<<"========"<<idx<<"cvjkcjvckjvckvjck"<<endl;
return F[idx]==-1?idx:F[idx]=Find(F[idx]);
}
int Kruskal()
{
sort(edge,edge+2*m);
memset(F,-1,sizeof(F));
int sum=0;
int ans=0;
for(int i=0;i<m*2;i++)
{
int be=edge[i].be;
int en=edge[i].en;
int dis=edge[i].dis;
// cout<<be<<" "<<en<<" "<<dis<<"---------"<<endl;
int idx1=Find(be);
int idx2=Find(en);
// cout<<idx1<<"==============="<<idx2<<endl;
if(idx1!=idx2)
{
F[idx2]=idx1;
ans+=dis;
sum++;
}
if(sum==n-1)
break;
}
if(sum!=n-1)
return INF;
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)==2&&n&&m)
{
for(int i=0;i<2*m;i+=2)
{
int a,b,c;
cin>>a>>b>>c;
edge[i].be=a;
edge[i].en=b;
edge[i].dis=c;
edge[i+1].be=b;
edge[i+1].en=a;
edge[i+1].dis=c;
}
int ans=Kruskal();
cout<<ans<<endl;
}
}