日常说明:首先博主也是菜鸟一枚,有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试
通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴
最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
运行截图:
MinSpanTree.h
#pragma once
#pragma once
#include<iomanip>
#include<iostream>
using namespace std;
#define max_v_num 100
#define INFINITY 10000
#define max 100
typedef int Boolean;
Boolean visited[max];
template <class T>
class Mgraph
{
public:
Mgraph(int vexs_num, int edge_num);
int Prim(Mgraph<T>prim_tree,int start);
int weight(int i, int j);
//private:
int vexs_num, edge_num;
T vexs[max_v_num];
int arc[max_v_num][max_v_num];
};
template<class T>
Mgraph<T>::Mgraph(int vexs_num, int edge_num)
{
this->vexs_num = vexs_num;
this->edge_num = edge_num;
cout << "请输入各顶点:";
for (int i = 0; i < vexs_num; i++)
{
cin >> vexs[i];
}
for (int i = 0; i < vexs_num; i++) //邻接矩阵初始化
{
for (int j = 0; j < edge_num; j++)
{
this->arc[i][j] = INFINITY;
}
}
cout << "请输入邻接矩阵下标i,j以及权值:" << endl;
for (int k = 0; k < edge_num; k++) //写入邻接矩阵元素
{
int i, j;
int w;
cin >> i >> j >> w;
arc[i][j] = arc[j][i] = w;
}
}
template<class T>
int Mgraph<T>::Prim(Mgraph<T>prim_tree,int start)
{
int temp[max];
int cost = 0;
int pose;
cout << prim_tree.vexs[start] << " ";
for (int i = 0; i < prim_tree.vexs_num; i++)
{
visited[i] = false;
if (i != start) temp[i] = prim_tree.arc[start][i];
}
visited[start] = true;
for (int i = 0; i < prim_tree.vexs_num-1; i++)
{
int min_weight = 1000;
for (int j = 0; j < prim_tree.vexs_num; j++)
{
if (!visited[j] && temp[j]<min_weight)
{
min_weight = temp[j];
pose = j;
}
}
cost += temp[pose];
visited[pose] = true;
cout <<prim_tree.vexs[pose] << " ";
for (int j = 0; j < prim_tree.vexs_num; j++)
{
if (!visited[j] && temp[j]>prim_tree.arc[pose][j])
{
temp[j] = prim_tree.arc[pose][j];
}
}
}
cout << "最小生成树的总代价为:";
return cost;
}
template<class T>
int Mgraph<T>::weight(int i,int j)
{
return arc[i][j];
}
MinSpanTree.cpp
#include"MinSpanTree.h"
int main()
{
int vexs_num, edge_num;
cout << "请输入顶点数和边数:";
cin >> vexs_num >> edge_num;
Mgraph<char>Graph(vexs_num, edge_num);
cout << "输出邻接矩阵:" << endl;
for (int i = 0; i < Graph.vexs_num; i++)
{
for (int j = 0; j < Graph.vexs_num; j++)
{
int w;
w = Graph.weight(i, j);
if (w == INFINITY)
{
cout << setw(6) << "∞";
}
else cout << setw(6) << w;
}
cout << endl;
}
cout << endl;
cout << "最小生成树:";
cout<< Graph.Prim(Graph,0)<<endl;
return 0;
}