prim-普利姆算法-MST-最小生成树

prim

对于顶点集的操作:

源码:

#include

using namespace std;

const int adjacent_matri_max=1000;

int vertex_num,edge_num;									//顶点数量 边数量
int	price=0;												//最小生成树代价 
int	adjacent_matri[adjacent_matri_max][adjacent_matri_max];	//邻接矩阵
bool visitied[adjacent_matri_max];							//定义标记数组 
int  l_cost[adjacent_matri_max];
int path[adjacent_matri_max];

//初始化邻接矩阵INT_MAX 
void init(){
	for(int i=0;i<vertex_num;i++){
		for(int j=0;j<vertex_num;j++){
			adjacent_matri[i][j]=INT_MAX;
		}
	}
	fill(visitied,visitied+vertex_num,false);
	fill(l_cost,l_cost+vertex_num,INT_MAX); 
	return ;
}

//Prim算法实现最小生成树 
void Prim(int key){
	//key  0-vertex 
	int k=0;
	path[k++]=key;
	do{
		visitied[key]=true;						//先把顶点设为访问 
		for(int i=0;i<vertex_num;i++){			//更新代价数组 
			l_cost[i]=min(l_cost[i],adjacent_matri[key][i]);	
		}
		int min_cost=INT_MAX;
		
		//找到之后下一轮才给路径 
		for(int i=0;i<vertex_num;i++){
			if(visitied[i]==false && l_cost[i]<min_cost){
				min_cost=l_cost[i];
				key=i;
			}
		}
		price+=min_cost;
		path[k]=key;
		cout<<k+1<<":"<<endl;
		cout<<"mint_cost:"<<min_cost<<endl;
		cout<<"price:"	<<price<<endl<<endl;
	}while(++k<vertex_num);
	
	return;
}

void PrintTree(int key){
	cout<<"最小生成树生成顺序:"<<endl;
//	cout<";
	int count=0;
	for(int i=0;i<vertex_num;i++){
//		if(key!=path[i]){
			cout<<path[i]<<" ";
//			if(count++!=vertex_num-2)
//				cout<<"->";
//		}
	}
}

int main(){
	int row,col;
	int key;
	int weight;
	cout<<"现在开始构造图:"<<endl;
	cout<<"请输入顶点数量:"<<endl;
	cin>>vertex_num;
	cout<<"请输入边的数量:"<<endl;
	cin>>edge_num;
	
	//初始化矩阵为INT最大值 	
	init();
	
	

	//生成图(邻接矩阵) 
	cout<<"请输入边(两个顶点表示)和边的权值:(共"<<edge_num<<"组(行))"<<endl;
	for(int i=0;i<edge_num;i++){
		cin>>row>>col;
		cin>>weight;
		adjacent_matri[row][col]=adjacent_matri[col][row]=weight;
	}
	
	for(int i=0;i<vertex_num;i++){
		for(int j=0;j<vertex_num;j++){
			cout<<adjacent_matri[i][j]<<" ";
		}
		cout<<endl;
	}
	
	cout<<"请输入起点顶点:"<<endl;	
	cin>>key;
	Prim(key);
	cout<<"最小生成树代价为:"<<price<<endl;		
 	PrintTree(key); 
	
	return 0;
} 

你可能感兴趣的:(数据结构与算法,C++)