最小生成树prim算法,一道模板题。
#include<iostream> #include<cstring> #include<cstdio> using namespace std; #define inf 9999999 int map[301][301],flag[301],vist[301],n,sum; void prim() { int i,j,v,MIN;sum=0; memset(vist,0,sizeof(vist)); memset(flag,0,sizeof(flag)); for(i=2;i<=n;i++) vist[i]=map[1][i]; vist[1]=0; flag[1]=1; for(i=2;i<=n;i++) { MIN=inf; for(j=1;j<=n;j++) { if(vist[j]<MIN&&!flag[j]) { MIN=vist[j]; v=j; } } sum+=MIN; flag[v]=1; for(j=1;j<=n;j++) { if(vist[j]>map[v][j]&&!flag[j]) vist[j]=map[v][j]; } } } int main() { int m,a,b,c,i; while(cin>>n) { if(n==0)break; cin>>m; if(m==0)cout<<"0"<<endl; else { memset(map,inf,sizeof(map)); for(i=1;i<=m;i++) { cin>>a>>b>>c; if(map[a][b]>c) map[a][b]=map[b][a]=c; } prim(); cout<<sum<<endl; } } return 0; }