#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const int maxn=1010,maxm=10010,INF=1000000000;
int a[maxn][maxn],d[maxn],p[maxn];
int main(){
#ifndef ONLINE_JUDGE
freopen("prim.in","r",stdin);
freopen("prim.out","w",stdout);
#endif
int i,j,k,m,n,s;
int x,y,w,ans=0,min;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)d[i]=INF;
for(i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&w);
a[x][y]=w;
a[y][x]=w;
}
d[1]=0;
for(i=1;i<=n;i++){
min=INF;
for(j=1;j<=n;j++)
if(!p[j] && d[j]<min){
min=d[j];
k=j;
}
p[k]=1;
ans+=d[k];
for(j=1;j<=n;j++)
if(a[k][j] && d[j]>a[k][j])
d[j]=a[k][j];
}
printf("%d\n",ans);
return 0;
}
最小生成树之PRIM-O(n^2)
最新推荐文章于 2022-06-26 01:53:36 发布