图之最大生成树
最大生成树思路与最小生成树类似,区别在与每次找最长的边和对应的顶点
采用prim写法
如图:
测试:
代码如下:
#include<iostream>
using namespace std;
int visited[10] = { 0 };
int dist[10];
int graph[10][10];
void fun()
{
int res, pos;
res = 0;
pos = 0;
cout << "顶点个数:" << endl;
int n;
cin >> n;
cout << endl;
cout << "邻接矩阵:" << endl;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> graph[i][j];
cout << endl;
cout << "起点:" << endl;
int start;
cin >> start;
visited[start] = 1;
cout << "路径:" << endl;
cout << start << " ";
for (int i = 1; i <= n; i++)
dist[i] = graph[start][i];
for (int k = 1; k < n; k++)
{
int max = -999;
for(int i=1;i<=n;i++)
if (visited[i] == 0 && dist[i] > max)
{
max = dist[i];
pos = i;
}
cout << pos << " ";
res += dist[pos];
visited[pos] = 1;
for (int j = 1; j <= n; j++)
if (visited[j] == 0 && dist[j] < graph[pos][j])
dist[j] = graph[pos][j];
}
cout << endl;
cout << "最大权值和:" << endl;
cout << res << endl;
}
int main()
{
fun();
return 0;
}