/*
* File name : graph_cmst_prim.cpp
* Function : 图的最小生成树 Prim算法 C++实现
* Created on : 2016年6月8日
* Author : beijiwei@qq.com
* Copyright : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途
input:
6 9
2 4 11
3 5 13
4 6 3
5 6 4
2 3 6
4 5 7
1 2 1
3 4 9
1 3 2
*/
#include <cstdio>
#include <iostream>
#pragma warning(disable:4996)
using namespace std;
#define M 20
#define INF 99999;
int edge_map[M][M];
int dis[M];
int mark[M];
int path[M];
int vertex_count = 0;
int weight_sum = 0;
int main(int argc, char** argv)
{
freopen("input.txt", "r", stdin);
int vertex_num, edge_num;
cin >> vertex_num >> edge_num;
for (int i = 1; i <= vertex_num; i++)//初始化邻接矩阵
{
for (int j = 1; j <= vertex_num; j++)
{
if (i == j)
edge_map[i][j] = 0;
else
edge_map[i][j] = INF;
}
}
for (int i = 1; i <= edge_num; i++)//读入边
{
int start, end, weight;
cin >> start >> end >> weight;
edge_map[start][end] = weight;
edge_map[end][start] = weight;//无向图
}
for (int i = 1; i <= vertex_num; i++)//初始化dis[],这里是一号顶点到其他顶点的距离
{
dis[i] = edge_map[1][i];
mark[i] = 0;
path[i] = 0;
}
mark[1] = 1;
vertex_count++;
path[0] = 1;
while (vertex_count <= vertex_num)
{
int min = INF;
int k = 0;
for (int i = 1; i <= vertex_num; i++)
{
if (mark[i] == 0 && min > dis[i])
{
min = dis[i];
k = i;
}
}
if (k == 0)
break;
mark[k] = 1;
path[vertex_count] = k;
vertex_count++;
weight_sum += dis[k];
for (int i = 1; i <= vertex_num; i++)
{
if (mark[i] == 0 && dis[i] > edge_map[k][i])
{
dis[i] = edge_map[k][i];
}
}
}
cout << "最短路径是: " << weight_sum << endl;
for (int i = 0; i < vertex_num; i++)
{
cout << "顶点是: " << path[i] << endl;
}
return 0;
}
图的最小生成树 Prim算法 C++实现
最新推荐文章于 2024-08-03 15:53:55 发布