我正在尝试使用 boost 的 prim 算法来使用边权重和 id 号而不是边权重来找到最小生成树。
例如,如果两个边的权重都是 1,则将比较 id,无论哪个较小,都会打破平局。
我创建了一个 EdgeWeight 类并重载了 < 和 + 运算符来执行此操作,然后将 edge_weight_t 属性从 int 更改为 EdgeWeight,希望它能起作用。
// TestPrim.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost/config.hpp>
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/prim_minimum_spanning_tree.hpp>
using namespace std;
class EdgeWeight{
public:
EdgeWeight(){}
EdgeWeight(int weightIn, int destinationIdIn){
weight = weightIn;
destinationId = destinationIdIn;
}
bool operator<(const EdgeWeight& rhs) const {
if (weight < rhs.weight)
return true;
else if(weight == rhs.weight){
if (destinationId < rhs.destinationId)
return true;
else
return false;
}
else
return false;
}
EdgeWeight operator+(const EdgeWeight& rhs) const {
EdgeWeight temp;
temp.weight = weight + rhs.weight;
temp.destinationId = destinationId + rhs.destinationId;
return temp;
}
int weight;
int destinationId;
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost;
typedef adjacency_list < vecS, vecS, undirectedS, property<vertex_distance_t, EdgeWeight>, property < edge_weight_t, EdgeWeight > > Graph;
typedef std::pair < int, int >E;
const int num_nodes = 5;
E edges[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),
E(3, 4), E(4, 0)
};
EdgeWeight weights[] = { EdgeWeight(1, 2), EdgeWeight(1, 3), EdgeWeight(2, 4),
EdgeWeight(7, 1), EdgeWeight(3, 3), EdgeWeight(1, 4), EdgeWeight(1, 0) };
Graph g(edges, edges + sizeof(edges) / sizeof(E), weights, num_nodes);
property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);
std::vector < graph_traits < Graph >::vertex_descriptor > p(num_vertices(g));
prim_minimum_spanning_tree(g, &p[0]);
for (std::size_t i = 0; i != p.size(); ++i)
if (p[i] != i)
std::cout << "parent[" << i << "] = " << p[i] << std::endl;
else
std::cout << "parent[" << i << "] = no parent" << std::endl;
return EXIT_SUCCESS;
}
我收到一个错误,“c:\program files (x86)\microsoft visual studio 10.0\vc\include\limits(92): error C2440: '' : cannot convert from 'int' to 'D' 1> No constructor could取源类型,或构造函数重载决议不明确”
我这样做对吗?有一个更好的方法吗?
http://www.boost.org/doc/libs/1_38_0/libs/graph/doc/prim_minimum_spanning_tree.html http://www.boost.org/doc/libs/1_38_0/boost/graph/prim_minimum_spanning_tree.hpp
编辑:好的,所以我现在使用 cjm 的扰动方法实现了权重,但是将来我相信我将不得不以某种方式使用上述方法,仍然想知道该怎么做
编辑2:根据耶利米的回应,我将 vertex_distance_t 从 int 更改为 EdgeWeight 但得到了同样的错误