prim:逐“点”生成最小生成树

与Dijkstra不同的是:加入点到生成树中,不要考虑与源点的距离,而是考虑与生成树的距离

#include <iostream>
#include <cstring>
using namespace std; const int VERTEX_NUM = 20;
const int INFINITY = 0x7fffffff; bool vis[VERTEX_NUM];
int dist[VERTEX_NUM];
int pre[VERTEX_NUM]; class Graph {
public:
int vexNum;
int edgeNum;
int vex[VERTEX_NUM];
int arc[VERTEX_NUM][VERTEX_NUM];
}; void createGraph(Graph &G)
{
cout << "please input vexNum and edgeNum: ";
cin >> G.vexNum >> G.edgeNum;
for (int i = 0; i != G.vexNum; ++i) {
cout << "please input no" << i+1 << " vertex: ";
cin >> G.vex[i]; // 自定义顶点序号
}
for (int i = 0; i != G.vexNum; ++i) {
for (int j = 0; j != G.vexNum; ++j) {
G.arc[i][j] = INFINITY;
}
}
for (int k = 0; k != G.edgeNum; ++k) {
cout << "please input the vertex of edge(vi, vj) and weight: ";
int i, j, w;
cin >> i >> j >> w;
G.arc[i][j] = w;
G.arc[j][i] = G.arc[i][j];
}
} void prim(Graph &G, int src)
{
memset(dist, INFINITY, VERTEX_NUM);
memset(vis, false, true);
for (int i = 0; i != G.vexNum; ++i) {
pre[i] = src;
dist[i] = G.arc[src][i];
}
vis[src] = true;
int lowcost;
int lowcostIndex;
for (int cnt = 1; cnt != G.vexNum; ++cnt) {
lowcost = INFINITY;
for (int i = 0; i != G.vexNum; ++i) {
if (dist[i] < lowcost && !vis[i]) {
lowcost = dist[i]; // 没意义,最小生成树考虑的是到生成树而不是源点
lowcostIndex = i;
}
}
vis[lowcostIndex] = true;
for (int i = 0; i != G.vexNum; ++i) {
if (G.arc[lowcostIndex][i] != INFINITY && G.arc[lowcostIndex][i] < dist[i] && !vis[i])
dist[i] = G.arc[lowcostIndex][i];
pre[i] = lowcostIndex;
}
}
} int main()
{
Graph G;
createGraph(G);
int src = 0;
prim(G, src);
int sum = 0;
for (int i = 0; i != G.vexNum; ++i) {
if (src == i) continue;
sum += dist[i];
}
cout << sum << endl;
}

  

最新文章

  1. Spring学习笔记之一----基于XML的Spring IOC配置
  2. mybatis中的#{}和${}
  3. sysobjects中字段的含义
  4. 边工作边刷题:70天一遍leetcode: day 71-2
  5. iOS完整学习步骤
  6. fastjson 常用api
  7. iOS开发必备HUD(透明指示层)
  8. HDU 1010 Tempter of the Bone --- DFS
  9. 2015南阳CCPC A - Secrete Master Plan 水题
  10. linux chmod 命令详解(转)
  11. poj 3667 Hotel (线段树)
  12. [Design Pattern] Front Controller Pattern 简单案例
  13. java模拟http post
  14. jQuery.extend()源码解读
  15. [SHOI2008]汉诺塔
  16. sql 数据库(表空间),用户 相关命令
  17. 【TCP/IP详解 卷一:协议】TCP定时器 小结
  18. Mac XMind8 保存时报错
  19. 微信小程序登录方案
  20. 如何查看Ext自带的API和示例

热门文章

  1. MySQL 5.7基于GTID的主从复制
  2. Java线程池的创建详解
  3. React Native开发之expo中camera的基本使用
  4. mongodb查看数据库和表的信息
  5. vuejs 解决跨域访问问题
  6. Elasticsearch 数据操作
  7. Redis,传统数据库,HBase,Hive区别联系
  8. EOJ Monthly 2019.3 A
  9. 小程序开发-11-Promise正确用法与函数签名设计技巧
  10. Java设计模式(1)——创建型模式之简单工厂模式(Simple Factory)