1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <iostream> using namespace std;
const int MaxSize = 10; int visited[MaxSize] = {0}; template <class DataType> class MGraph { public: MGraph(DataType a[ ], int n, int e); ~MGraph( ){ }; void Prim(int v); private: DataType vertex[MaxSize]; int edge[MaxSize][MaxSize]; int vertexNum, edgeNum;
int MinEdge(int r[ ], int n); }; template <class DataType> MGraph<DataType> :: MGraph(DataType a[ ], int n, int e) { int i, j, k, w; vertexNum = n; edgeNum = e; for (i = 0; i < vertexNum; i++) vertex[i] = a[i]; for (i = 0; i < vertexNum; i++) for (j = 0; j < vertexNum; j++) if (i == j) edge[i][j] = 0; else edge[i][j] = 100; for (k = 0; k < edgeNum; k++) { cout << "请输入边依附的两个顶点的编号,以及边上的权值:"; cin >> i >> j >> w; edge[i][j] = w; edge[j][i] = w; } }
template <class DataType> void MGraph<DataType> :: Prim(int v) { int i, j, k; int adjvex[MaxSize], lowcost[MaxSize]; for (i = 0; i < vertexNum; i++) { lowcost[i] = edge[v][i]; adjvex[i] = v; } lowcost[v] = 0; for (k = 1; k < vertexNum; k++) { j = MinEdge(lowcost, vertexNum); cout << "(" << vertex[j] << "," << vertex[adjvex[j]] << ")" << lowcost[j] << endl; lowcost[j] = 0; for (i = 0; i < vertexNum; i++) if (edge[i][j] < lowcost[i]) { lowcost[i] = edge[i][j]; adjvex[i] = j; } } }
template <class DataType> int MGraph<DataType> :: MinEdge(int r[ ], int n) { int index = 0, min = 100; for (int i = 1; i < n; i++) if (r[i] != 0 && r[i] < min) { min = r[i]; index = i; } return index; }
int main( ) { char ch[ ]={'A','B','C','D','E','F'}; MGraph<char> MG{ch, 6, 9}; MG.Prim(0); return 0; }
|