最小生成树——Prim

来源:互联网 发布:淘宝年费多少钱 编辑:程序博客网 时间:2024/05/20 09:25

头文件"AdjGraph.h"

#include<iostream>#define VISITED 1#define UNVISITED 0#define INFINITY 1000using namespace std;class AdjGraph{public:int **edge;//边,值为权值int *low;//最小权值int *mark;//记录结点是否被标记int vertexNum,edgeNum;//边,结点数目AdjGraph(){vertexNum=0;edgeNum=0;}~AdjGraph(){for(int i=0;i<vertexNum;i++)delete [] edge[i];delete [] edge;delete [] low;delete [] mark;}void creatGraph(int num){vertexNum=num;mark=new int [num];low=new int [num];edge=new int *[num];for(int i=0;i<num;i++)edge[i]=new int [num];for(int i=0;i<num;i++){mark[i]=UNVISITED;for(int j=0;j<num;j++)edge[i][j]=INFINITY;}}void setedge(int v,int u,int weight){edge[v][u]=weight;edge[u][v]=weight;edgeNum++;}int prim(){int pos=0;int min;int result=0;mark[0]=VISITED;for(int i=0;i<vertexNum;i++)low[i]=edge[pos][i];//寻找最小权值路径,循环vertexNum-1次for(int i=1;i<vertexNum;i++){min=INFINITY;for(int j=0;j<vertexNum;j++){if(mark[j]==UNVISITED&&min>low[j]){min=low[j];pos=j;}}//输出最小生成树for(int p=0;p<vertexNum;p++)if((edge[pos][p]==min||edge[p][pos]==min)&&mark[p]==VISITED)cout<<"v"<<p+1<<"->"<<"v"<<pos+1<<endl;mark[pos]=VISITED;result+=min;//更新最小权值数组for(int k=0;k<vertexNum;k++){if(mark[k]==UNVISITED&&low[k]>edge[pos][k])low[k]=edge[pos][k];}}return result;}};


源文件"main.cpp"

#include<iostream>#include"AdjGraph.h"using namespace std;int main(){AdjGraph AG; int result;AG.creatGraph(6);AG.setedge(0,1,6);AG.setedge(0,2,1);AG.setedge(0,3,5);AG.setedge(1,2,5);AG.setedge(1,4,3);AG.setedge(2,3,5);AG.setedge(2,4,6);AG.setedge(2,5,4);AG.setedge(3,5,2);AG.setedge(4,5,6);result=AG.prim();cout<<result<<endl;return 0;}


原创粉丝点击