#include "iostream"
#include "vector"
#include "fstream"
using namespace std;
std::vector<vector<double> > weight;
int vertexnum;
int edgenum;
void initialvector(){
weight.resize(vertexnum);
for(int i = 0; i< vertexnum; i++){
weight[i].resize(vertexnum,100000.0);
}
}
void getData()
{
ifstream in("data");
in>>vertexnum>>edgenum;
initialvector();
int from,to;
double weight1;
while(in>>from>>to>>weight1){
weight[from][to] = weight1;
weight[to][from] = weight1;
}
}
void prim(){
std::vector<double> lowcost(vertexnum);
std::vector<int> closeset(vertexnum);
std::vector<bool> mark(vertexnum);
for(int i = 1;i < vertexnum;i++){
lowcost[i] = weight[0][i];
closeset[i] = 0;
mark[0] = true;//把节点0添加到closeset中
mark[i] = false;
}
for(int i = 0;i < vertexnum;i++){
double min = 100000.0;int j = 0;
for(int k = 1;k < vertexnum;k++){ //在剩余节点中,选择离closeset距离最近的点
if(lowcost[k] < min && !mark[k]){
min = lowcost[k];
j = k;
}
}
mark[j] = true; /*添加j节点到closeset集合*/
for(int k = 1;k < vertexnum;k++){
if(weight[j][k] < lowcost[k] && !mark[k]){
lowcost[k] = weight[j][k];//更新lowcost
closeset[k] = j;
}
}
}
for(int i = 0;i < vertexnum ;i++){
cout<<closeset[i]<<"->"<<i<<endl;
}
}
int main(int argc, char const *argv[])
{
getData();
for(int i = 0;i < vertexnum;i++){
for(int j = 0;j < vertexnum;j++){
cout<<weight[i][j]<<"\t";
}
cout<<endl;
}
prim();
return 0;
}
8 16
4 5 0.35
4 7 0.37
5 7 0.28
0 7 0.16
1 5 0.32
0 4 0.38
2 3 0.17
1 7 0.19
0 2 0.26
1 2 0.36
1 3 0.29
2 7 0.34
6 2 0.40
3 6 0.52
6 0 0.58
6 4 0.93
参考:http://blog.lchx.me/index.php/%E6%9C%80%E5%B0%8F%E7%94%9F%E6%88%90%E6%A0%91prim%E7%AE%97%E6%B3%95/