我正在尝试使用boost的prim的算法来找到使用边权重和id号代替边缘权重的最小生成树。带自定义权重的C++ boost prim算法?
例如,如果两个边权重都是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)的\微软的Visual Studio 10.0 \ VC \包括\限制(92):错误C2440:':诠释 '到'无法从转换' D' 1>没有构造函数可以采取源类型,或构造函数重载分辨率模糊“
我正在做这个正确的方式吗?有一个更好的方法吗?
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
编辑:好了,所以我实现了使用军事审判的摄动法求现在的权重,但在将来,我相信我会以某种方式使用上述方法,仍然不知道该怎么办呢
EDIT2:根据耶利米的效应初探我改变了vertex_distance_t从int到EdgeWeight,但得到了同样的错误
似乎这样的错误它不会有什么做的算法?该文件的第92行是什么?你可以把这个错误出现在哪里? – 2012-04-11 00:48:35
我认为一个简单的打破关系的方法就是扰动边缘权重的一小部分。例如。如果您的边缘权重最初是整数,那么对于重量为5的两个边,使其中一个重量为4.9,另一个重量为5.1。你如何扰乱事情显然取决于你期望有多少关系/你的边权重的领域。 – cjm 2012-04-11 00:56:37
我可以这样做,我猜。我试图用类型来做到“正确”的方式。 – stack356 2012-04-11 02:08:04