并查集+prime
第一次写prim。。。
#include"stdio.h" #define max 99999999 int main() { int map[100][100],dist[100]; int flag,ans; int i,j,k,t,temp; int n,m,a,b,dis; while(scanf("%d%d",&n,&m)!=EOF&&n) { ans=0;flag=1; for(i=1;i<=m;i++) { for(j=1;j<=m;j++) map[i][j]=max; } for(i=1;i<=m;i++) map[i][i]=0; for(i=1;i<=n;i++) { scanf("%d%d%d",&a,&b,&dis); map[a][b]=map[b][a]=dis; } dist[1]=0; for(i=2;i<=m;i++) dist[i]=map[1][i]; for(i=1;i<=m-1;i++) { temp=max; for(j=2;j<=m;j++) { if(dist[j]<temp&&dist[j]>0) { temp=dist[j]; t=j; } } dist[t]=0; if(temp==max) { flag=0;break; } else ans+=temp; for(k=2;k<=m;k++) { if(dist[k]>map[t][k]) dist[k]=map[t][k]; } } if(flag==0) printf("?\n"); else printf("%d\n",ans); } return 0; }