文章目录
- 参考文章
- 目的
- c++实现
参考文章
点击访问
目的
实现参考文章
中的图结构,并计算它的最小生成树
c++实现
#include<iostream>
#include<vector>
#include<map>
class Node
{
public:
Node(const int val) :value(val) {}
int value;
std::map<int, int> edges;
};
class PrimAlgorithm
{
public:
bool prim(const std::vector<Node>& all_nodes,
std::vector<Node>& prim_nodes, int& sum_result);
bool updateDist(Node& node, std::vector<int>& dist);
};
bool PrimAlgorithm::prim(const std::vector<Node>& all_nodes,
std::vector<Node>& prim_nodes, int& sum_result)
{
int size = all_nodes.size();
std::vector<int> dist(size+1, INT_MAX);
dist[0] = -1; // 不使用index=0的索引
/*for (const auto& item : dist) std::cout << item << " ";
std::cout << std::endl;*/
Node randNode = all_nodes[0];
prim_nodes.push_back(randNode);
dist[1] = 0;
for (int i = 1; i < size; ++i)
{
Node node = prim_nodes[prim_nodes.size() - 1];
updateDist(node, dist);
/*for (const auto& item : dist) std::cout << item << " ";
std::cout << std::endl;*/
// 选择dist大于0且值最小的那个顶点
int minVal = INT_MAX;
int minIndex = 0;
for (int j = 1; j < dist.size(); ++j)
{
if (dist[j] > 0 && dist[j] < minVal)
{
minVal = dist[j];
minIndex = j;
}
}
sum_result += minVal;
//std::cout << "minIndex=" << minIndex << std::endl;
for (const auto& node : all_nodes)
{
if (node.value == minIndex)
{
prim_nodes.push_back(node);
break;
}
}
dist[minIndex] = 0; // 将这个位置的dist置0, 因为它已经在最小生成树里了
}
return true;
}
bool PrimAlgorithm::updateDist(Node& node, std::vector<int>& dist)
{
//std::cout << "node.vale=" << node.value << std::endl;
for (int i = 1; i < dist.size(); ++i)
{
if (node.edges.find(i) == node.edges.end()) continue; // 没有这个邻边
else
{
if (node.edges[i] < dist[i])
{
dist[i] = node.edges[i]; // 更新dist
//std::cout << "i=" << i << ", dist[i]=" << node.edges[i] << std::endl;
}
}
}
return true;
}
int main()
{
std::vector<Node> allNodes;
Node one(1);
one.edges[7] = 36;
one.edges[2] = 23;
one.edges[6] = 28;
allNodes.push_back(one);
Node two(2);
two.edges[1] = 23;
two.edges[7] = 1;
two.edges[3] = 20;
allNodes.push_back(two);
Node three(3);
three.edges[2] = 20;
three.edges[7] = 4;
three.edges[4] = 15;
allNodes.push_back(three);
Node four(4);
four.edges[3] = 15;
four.edges[7] = 9;
four.edges[5] = 3;
allNodes.push_back(four);
Node five(5);
five.edges[4] = 3;
five.edges[7] = 16;
five.edges[6] = 17;
allNodes.push_back(five);
Node six(6);
six.edges[1] = 28;
six.edges[7] = 25;
six.edges[5] = 17;
allNodes.push_back(six);
Node seven(7);
seven.edges[1] = 36;
seven.edges[2] = 1;
seven.edges[3] = 4;
seven.edges[4] = 9;
seven.edges[5] = 16;
seven.edges[6] = 25;
allNodes.push_back(seven);
std::vector<Node> primNodes;
int sumResult = 0;
PrimAlgorithm pag;
pag.prim(allNodes, primNodes, sumResult);
for (const auto& node : primNodes)
{
std::cout << node.value << " ";
}
std::cout<<std::endl;
std::cout << "dist all = " << sumResult << std::endl;
return 0;
}
与预期一致