基于邻接矩阵,循环n-1次,每次加入一个结点。
把加入节点的集合(设为G)和未加入节点的集合看成二分图,找到一条最短边并把这条边对应的那个在未加入节点的集合里的那个点加入节点集,G不断扩大,最终包括所有节点。
//最短树的Prim算法
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100;
const int Max = 0x7fffffff;
int graph[N][N];
bool vis[N];
int n,m;
int len = 0;
int find_node()
{
int l = Max;
int k = 1;
for (int i = 1; i <= n; i++)
{
if (vis[i])
{
for (int j = 1; j <= n; j++)
{
if (!vis[j] && graph[i][j] < l)
l = graph[i][j], k = j;
}
}
}
len += l;
cout << k << " have been added " << endl;
vis[k] = 1;
return k;
}
void Prim()
{
vis[1] = 1;
for (int i = 1; i < n; i++) //循环n-1次
find_node();
}
int main()
{
cout << "Please input the number of nodes : ";
cin >> n;
cout << "Please input the number of edges : ";
cin >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
graph[i][j] = Max;
int vi,vj,th;
for (int i = 0; i < m; i++)
{
cin >> vi >> vj >> th;
graph[vi][vj] = graph[vj][vi] = th;
}
cout << "input ended" << endl;
Prim();
cout << "The length of the shortest tree path is ";
cout << len << endl;
return 0;
}