一个有 n 个结点的连通图的生成树是原图的极小连通子图,且包含原图中的所有 n 个结点,并且有保持图连通的最少的边。
今天看了普利姆算法.记录一下.
<pre name="code" class="cpp">// bogo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <stdio.h> #include <iostream> using namespace std; #define MAX_PATH 65535 int date[9][9] = { {0,10,MAX_PATH,MAX_PATH,MAX_PATH,11,MAX_PATH,MAX_PATH,MAX_PATH}, {10,0,18,MAX_PATH,MAX_PATH,MAX_PATH,16,MAX_PATH,12}, {MAX_PATH,MAX_PATH,0,22,MAX_PATH,11,MAX_PATH,MAX_PATH,8}, {MAX_PATH,MAX_PATH,22,0,20,MAX_PATH,MAX_PATH,16,21}, {MAX_PATH,MAX_PATH,MAX_PATH,20,0,26,MAX_PATH,7,MAX_PATH}, {11,MAX_PATH,MAX_PATH,MAX_PATH,26,0,17,MAX_PATH,MAX_PATH}, {MAX_PATH,16,MAX_PATH,MAX_PATH,MAX_PATH,17,0,19,MAX_PATH}, {MAX_PATH,MAX_PATH,MAX_PATH,16,7,MAX_PATH,19,0,MAX_PATH}, {MAX_PATH,12,8,21,MAX_PATH,MAX_PATH,MAX_PATH,MAX_PATH,0} }; int _tmain(int argc, _TCHAR* argv[]) { int lowest[9];//这个数组可以理解为下标为i的点,与现在已经加入生成树各点的最小权值. int adjvex[9];//a[i] = k 就是表示i点与树中的k点之间权值最小.如果目前树种没有与i相连,则a[i] = 0 int min; int j,k; int length = 9; lowest[0] = 0; adjvex[0] = 0; int i; //初始化 for (i = 1; i < length; i++) { adjvex[i] = 0; lowest[i] = date[0][i]; } for (i = 1; i < length; i++) { //初始化最小权值为MAX min = MAX_PATH; j = 1; k = 0; while (j < length) { if (lowest[j] != 0&&lowest[j] < min) { min = lowest[j]; k = j; } j++; } printf("%d %d ",adjvex[k],min); lowest[k] = 0;//表示此点已经加入了最小生成树 for (j = 1; j < length; j++) { if (lowest[j] != 0&&date[k][j] < lowest[j]) { lowest[j] = date[k][j]; adjvex[j] = k; } } } return 0; }