我正在嘗試使用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