• 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 "); 108 }

    Kruskal算法:

    还未更新,敬请期待....

  • 相关阅读:
    .NET日志系统
    新建elasticsearch 车辆表索引
    mysqlconnectjava.jar下载地址
    mac安装mysql5.7
    window使用logstashinputjdbc同步数据到es
    如何降低node 包版本
    ansible的介绍与hosts文件(一)
    ansible的模块的使用(二)
    爬虫分布式爬虫(未完成)
    前端页面布局链接
  • 原文地址:https://www.cnblogs.com/2293002826PYozo/p/11407060.html
Copyright © 2020-2023  润新知