08-图7 公路村村通 (30 分)
Posted 2293002826pyozo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了08-图7 公路村村通 (30 分)相关的知识,希望对你有一定的参考价值。
/*prim算法*/
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define MAX 1002 4 #define INF 500001 5 6 typedef int Vertex; 7 typedef int Weight; 8 9 typedef struct ENode* Edge; 10 struct ENode 11 Vertex V1; 12 Vertex V2; 13 Weight W; 14 ; 15 16 typedef struct GNode* MGraph; 17 struct GNode 18 int N; 19 int M; 20 Vertex G[MAX][MAX]; 21 ; 22 MGraph CreateGraph(); 23 MGraph BuildGraph(); 24 void InsertVertex(MGraph Graph, Edge E); 25 void Prim(MGraph Graph, Vertex dist[], Vertex parent[]); 26 27 int main() 28 29 MGraph Graph; 30 Vertex dist[MAX], parent[MAX]; 31 for (int i = 0; i < MAX; i++) 32 33 dist[i] = INF; 34 parent[i] = 0; 35 36 Graph = BuildGraph(); 37 Prim(Graph, dist, parent); 38 39 40 MGraph CreateGraph() 41 42 MGraph Graph = (MGraph)malloc(sizeof(struct GNode)); 43 scanf("%d%d", &Graph->N, &Graph->M); 44 for (int i = 0; i < Graph->N; i++) 45 for (int j = 0; j < MAX; j++) 46 Graph->G[i][j] = Graph->G[j][i] = INF; 47 return Graph; 48 49 50 MGraph BuildGraph() 51 52 MGraph G; 53 Edge E = NULL; 54 E = (Edge)malloc(sizeof(struct ENode)); 55 G = CreateGraph(); 56 int i; 57 for (i = 0; i < G->M; i++) 58 59 scanf("%d%d%d", &E->V1, &E->V2, &E->W); 60 InsertVertex(G, E); 61 62 return G; 63 64 65 void InsertVertex(MGraph Graph, Edge E) 66 67 Graph->G[E->V1][E->V2] = Graph->G[E->V2][E->V1] = E->W; 68 69 70 int FindMinDist(MGraph Graph, Vertex dist[],Vertex parent[]) 71 int v, MinDist = INF, Minv = 0; 72 for (v = 0; v <= Graph->N; v++) 73 74 if (dist[v]!=0 && dist[v] < MinDist) 75 MinDist = dist[v]; 76 Minv = v; 77 78 79 if (MinDist == INF||Minv==0) return 0; 80 return Minv; 81 82 83 void Prim(MGraph Graph, Vertex dist[], Vertex parent[]) 84 85 int i, MST=0, V,cost=0; 86 for (i = 0; i <= Graph->N; i++) 87 88 if (Graph->G[1][i] != INF) parent[i] = 1; 89 else parent[i] = -1; 90 dist[i] = Graph->G[1][i]; 91 92 dist[1] = 0; 93 while (1) 94 V = FindMinDist(Graph, dist,parent); 95 if (V == 0) break; 96 cost += dist[V]; 97 dist[V] = 0;MST++; 98 for (i = 0; i < Graph->N; i++) 99 if (dist[i] != 0) 100 if (Graph->G[V][i] < dist[i]) 101 102 dist[i] = Graph->G[V][i]; 103 parent[i] = V; 104 105 106 if (MST == Graph->N-1) printf("%d", cost); 107 else printf("-1\n"); 108
Kruskal算法:
还未更新,敬请期待....
以上是关于08-图7 公路村村通 (30 分)的主要内容,如果未能解决你的问题,请参考以下文章