最小生成树MST
最小生成树定义:
一个有 n 个结点的连通图的生成树是原图的极小连通子图,且包含原图中的所有 n 个结点,并且有保持图连通的最少的边。
Prim algorithm:
Prim算法简述
1).输入:一个加权连通图,其中顶点集合为V,边集合为E;
2).初始化:Vnew= {x},其中x为集合V中的任一节点(起始点),Enew= {},为空;
3).重复下列操作,直到Vnew= V:
a.在集合E中选取权值最小的边<u, v>,其中u为集合Vnew中的元素,而v不在Vnew集合当中,并且v∈V(如果存在有多条满足前述条件即具有相同权值的边,则可任意选取其中之一);
b.将v加入集合Vnew中,将<u, v>边加入集合Enew中;
4).输出:使用集合Vnew和Enew来描述所得到的最小生成树。
#include <iostream>
#include <vector>
using namespace std;
#define MAXCOST 10000000
#define Max 100
//使用0,1,2,...,n表示结点
typedef float Weight;
typedef int Vertex;
typedef float Edges;
Weight graph[Max][Max] = {};
void get_graph(int e){
for(int i = 0;i < e;i++){
Vertex v1,v2;
Weight w;
cin >> v1 >> v2 >> w;
graph[v1][v2] = graph[v2][v1] = w;
}
}
// only return the smallest weight of the graph
Weight Prim(int n){
//将V0加入
Weight total = 0; //the smallest total weight
Vertex newVertex; // the vertex which add each time
Vertex MST[n]={};// the set of vertex
Edges min_edges[n]={};// the set of edge
//数组MST 等于-1表示该点已经加入,不等于-1表示该点与已经加入MST中的点最小权值的那个点
for(int i = 1;i < n;i++){
if(graph[0][i] != 0)
min_edges[i] = graph[0][i];
else
min_edges[i] = MAXCOST;
MST[i] = 0;
}
MST[0] = -1;
//找到下一个加入的点
for(int i = 1;i <= n-1;i++){
Weight min_path = MAXCOST;
for(int j = 0;j < n;j++)
if(min_edges[j] < min_path && MST[j]!=-1)
min_path = min_edges[j] , newVertex = j;
cout << "Point" << MST[newVertex] << " to "<< "Point" << newVertex << " = " << min_path << endl; //print the graph
MST[newVertex] = -1; //like erase the new vertex in total vertex
total += min_path;
min_edges[newVertex] = 0;
//重新对未加入的点与MST中的点的最小权值重新赋值
for(int k = 0;k < n;k++)
if(min_edges[k] > graph[newVertex][k] && MST[k]!=-1 && graph[newVertex][k] != 0)
min_edges[k] = graph[newVertex][k],MST[k] = newVertex;
}
return total;
}
int main(){
cout << "Prim algorithm" << endl;
int n; //点的个数
cin >> n;
int edge ; //边的个数
cin >> edge;
get_graph(edge);
cout << "The smallest weight of the graph: " << Prim(n) << endl;
return 0;
}
参考: