PRIM
#include<iostream> #include<cstdlib> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; const int maxn=99999999; int n,m,cnt=1,ans,e[1005][1005],dis[1005],book[1005]; int main() { int i,j,a,b,c; scanf("%d%d",&n,&m); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(i==j) e[i][j]; else e[i][j]=maxn; } } book[1]=1; for(i=1;i<=m;i++) { scanf("%d%d%d",&a,&b,&c); e[a][b]=c; e[b][a]=c; } for(i=1;i<=n;i++) dis[i]=e[1][i]; while(cnt<n) { int minn=maxn,u; for(j=1;j<=n;j++) { if(dis[j]<minn && book[j]==0) { minn=dis[j]; u=j; } } book[u]=1; cnt++; ans+=dis[u]; for(j=1;j<=n;j++) { if(e[u][j]<maxn) { if(dis[j]>e[u][j]) dis[j]=e[u][j]; } } } //for(i=1;i<=n;i++) ans+=dis[i]; printf("%d",ans); return 0; } /* 6 9 2 4 11 3 5 13 4 6 3 5 6 4 2 3 6 4 5 7 1 2 1 3 4 9 1 3 2 */