一、实验名称:最小代价生成树
二、实验目的:
1.掌握贪心算法解决问题的思想和一般过程,
2.学会使用普里姆算法解决实际问题。
三、实验内容
完善下列程序,并回答问题。
1 #include<iostream.h> 2 #define G_NODE_NUM 6 //结点个数 3 #define INFTY 65535 4 template<class T> 5 struct ENode 6 {//带权图的边结点 7 int adjVex; 8 T w; 9 ENode* nextArc; 10 }; 11 template <class T> 12 class Graph 13 { 14 public: 15 Graph (int mSize){ 16 n = mSize; 17 a = new ENode<T> *[mSize]; 18 for(int i = 0; i< n ;i++){ 19 a[i] = NULL; 20 } 21 } 22 void Prim(int s); 23 void putin(T X[G_NODE_NUM][G_NODE_NUM]); 24 void putout(); 25 protected: 26 void Prim(int k, int* nearest, T* lowcost); 27 ENode<T>** a; 28 int n; 29 }; 30 31 template<class T> 32 void Graph<T>::putin(T X[G_NODE_NUM][G_NODE_NUM]){ 33 ENode<T> *e; 34 for(int i = 0; i < n; i++){ 35 for(int j = 0; j < n; j++){ 36 if(X[i][j]>0){ 37 e = new ENode<T>(); 38 e->adjVex = j; 39 e->w = X[i][j]; 40 e->nextArc = a[i]; 41 a[i] = e; 42 } 43 } 44 } 45 } 46 template<class T> 47 void Graph<T>::putout(){ 48 ENode<T> *e; 49 cout<<"---图输出---"<<endl; 50 for(int i=0; i<n; i++){ 51 e = a[i]; 52 cout<<endl<<"第"<<i<<"个节点:"; 53 while(e!=NULL){ 54 cout<<" "<<e->adjVex<<"("<<e->w<<")"; 55 e=e->nextArc; 56 } 57 } 58 cout<<endl; 59 } 60 61 template<class T> 62 void Graph<T>::Prim(int s) 63 { 64 学生书写部分 65 }; 66 67 template<class T> 68 void Graph<T>::Prim(int k, int* nearest, T* lowcost) 69 { 70 学生书写部分 71 } 72 73 void main(){ 74 Graph<int> *G; 75 int data[G_NODE_NUM][G_NODE_NUM]={ {0,6,1,5,0,0}, 76 {6,0,5,0,3,0}, 77 {1,5,0,5,6,4}, 78 {5,0,5,0,0,2}, 79 {0,3,6,0,0,6}, 80 {0,0,4,2,6,0}}; 81 int n = G_NODE_NUM; 82 G = new Graph<int>(n); 83 G->putin(data); 84 G->putout(); 85 G->Prim(0); 86 }