标签:hide ffffff gif min sed code cdc div splay
1 #include<stdio.h> 2 #include<string.h> 3 #define MAXN 1001 4 #define INF 0x3fffffff 5 int n,m,g[MAXN][MAXN],vis[MAXN],dist[MAXN]; 6 void read(); 7 int prim(); 8 int main(){ 9 read(); 10 int cost = prim(); 11 printf("%d\n",cost); 12 return 0; 13 } 14 void read(){ 15 scanf("%d %d",&n,&m); 16 int i,j,v1,v2,cost1; 17 for(i=1;i<=n;i++) 18 for(j=1;j<=n;j++) 19 g[i][j] = INF; 20 for(i=1;i<=m;i++){ 21 scanf("%d %d %d",&v1,&v2,&cost1); 22 g[v1][v2] = cost1; 23 g[v2][v1] = cost1; 24 } 25 } 26 int prim(){ 27 int cost,i,j; 28 for(i=1;i<=n;i++){ 29 dist[i] = INF; 30 vis[i] = 0; 31 } 32 dist[1] = 0; 33 vis[1] = 1; 34 for(i=1;i<=n;i++) 35 if(g[1][i]!=INF&&i!=1) 36 dist[i] = g[1][i]; 37 cost = 0; 38 while(1){ 39 int mdist=INF,mindex=-1; 40 for(i=1;i<=n;i++){ 41 if(mdist>dist[i] && vis[i]==0){ 42 mdist = dist[i]; 43 mindex = i; 44 } 45 } 46 if(mindex==-1) break; 47 cost += mdist; 48 vis[mindex] = 1; 49 for(i=1;i<=n;i++){ 50 if(g[mindex][i]!=INF && i!=mindex && vis[i]==0){ 51 if(dist[i]>g[mindex][i]) dist[i] = g[mindex][i]; 52 } 53 } 54 } 55 int vsum=0; 56 for(i=1;i<=n;i++) vsum += vis[i]; 57 if (vsum==n) return cost; 58 else return -1; 59 60 61 }
标签:hide ffffff gif min sed code cdc div splay
原文地址:https://www.cnblogs.com/Learn-Excel/p/12638638.html