zoukankan      html  css  js  c++  java
  • 【算法与数据结构】图的最小生成树 MST

    Prim 算法属于贪心算法。

    #include <stdio.h>
    #define VERTEXNUM 7
    #define INF 10000
    
    typedef struct Graph {
    	int vertex[VERTEXNUM];
    	int edge[VERTEXNUM][VERTEXNUM];
    } Graph;
    
    void initGraph(Graph* G) {
    	int i, j;
    	int init[][3] = {{1, 2, 10}, {1, 3, 8}, {1, 6, 20},
    					{2, 3, 3}, {2, 5, 30}, {3, 4, 18},
    					{3, 6, 7}, {4, 5, 2}, {6, 7, 1}};
    	for (i = 0; i < VERTEXNUM; i++) {
    		G->vertex[i] = 'a' + i;
    		for (j = 0; j < VERTEXNUM; j++) {
    			G->edge[i][j] = INF;
    		}
    	}
    	for (i = 0; i < 9; i++) {
    		G->edge[init[i][0] - 1][init[i][1] - 1] = init[i][2];
    		G->edge[init[i][1] - 1][init[i][0] - 1] = init[i][2];
    	}
    }
    
    void prim(Graph* G) {
    	int parent[VERTEXNUM];
    	int selected[VERTEXNUM];
    	int nearest[VERTEXNUM];
    	int i, j, k, lastVer, min;
    	for (i = 0; i < VERTEXNUM; i++) {
    		parent[i] = -1;
    		selected[i] = 0;
    		nearest[i] = INF;
    	}
    	lastVer = 0;
    // 	selected[0] = 1;
    	for (i = 0; i < VERTEXNUM; i++) {
    		if (G->edge[0][i] < INF) {
    			parent[i] = 0;
    			nearest[i] = G->edge[0][i];
    		}
    	}
    	for (i = 1; i < VERTEXNUM; i++) {
    		min = INF;
    		if (selected[lastVer] == 1)
    			continue;
    		selected[lastVer] = 1;
    		for (j = 0; j < VERTEXNUM; j++) {
    			if (G->edge[lastVer][j] < nearest[j]) {
    				parent[j] = lastVer;
    				nearest[j] = G->edge[lastVer][j];
    			}
    		}
    		for (j = 0; j < VERTEXNUM; j++) {
    			if (selected[j] != 1 && nearest[j] < min) {
    				min = nearest[j];
    				lastVer = j;
    			}
    		}
    		printf("lastVer: %d
    ", lastVer);
    	}
    }
    int main () {
    	Graph G;
    	initGraph(&G);
    	
    	prim(&G);
    	return 0;
    }
    
  • 相关阅读:
    Git/GitHub使用技巧
    《暗时间》第一遍读书心得整理
    学习方法摘要总结
    Py爬虫项目
    2018年6月12日
    狐狸坑蛋糕
    Codeforces 371C Hanburgers
    【别忘咯】 关于运算优先级
    【noip 2009】 乌龟棋 记忆化搜索&动规
    【Openjudge】 算24
  • 原文地址:https://www.cnblogs.com/kika/p/10851493.html
Copyright © 2011-2022 走看看