[英]BGL - Custom Visitor that weights edge weights by previous step
我有一個有向圖,我知道它沒有任何循環依賴關系並且有“終止”節點,即它們有一個自定義頂點屬性,這是一個我可以檢查的布爾值。 每條邊都使用 BGL 內置邊權重屬性加權。
我想要做的是沿着所有可能的路徑從任何頂點走,直到它到達所有可以到達的終止節點並跟蹤到達的每個終止節點的“加權”邊權重。 我的意思是通過以下簡單示例可以最好地解釋以下內容。
從節點 4 開始,有以下帶權重的邊,如果 T(終止)
4->1 : 0.25 : T
4->5 : 0.45
4->6 : 0.5
5->2 : 0.65 : T
6->3 : 0.18
6->7 : 0.44 : T
3->1 : 0.33 : T
我想返回一個對的向量,它是在到達每個節點的路上行走的邊緣權重的終止節點/“加權”組合,在這種情況下是:
{1, 0.25 + (0.5*0.18*0.33) }
{2, (0.45*0.65)}
{7, (0.5*0.44)}
Final Result : [ {1, 0.2797}, {2, 0.2925}, {7, 0.22}]
通過“加權”,我的意思是每個新步驟都由在特定路徑上行走的所有先前邊緣權重的乘積加權。
所以從4到終端節點1,有兩條路徑。 直接邊為 1,權重為 0.25。 還有一條路徑是 4->6->3->1,所以是 0.5*0.18*0.33。 因此,對於節點 1,我們的總權重為 0.25 + (0.5*0.18*0.33) = 0.2797。
再次從 4 到終止節點 2,有一條到 4->5->2 (0.45*0.65) 的路徑,所以節點 2 = 0.2925
最后 4 到終止節點 7,路徑 4->6->7,(0.5*0.44),所以節點 7 = 0.22
這在 BGL 中是否可行,我想我需要某種自定義訪問者/前任?
非常感謝任何幫助。
您的示例計算非常混亂。 我假設您打算按照您的描述進行操作: “在到達每個節點的路上行走的加權邊權重的總和” ,因此:
{1, 0.25}
{2, (0.45+0.65)}
{7, (0.5+0.44)}
Final Result : [ {1, 0.25}, {2, 1.1}, {7, 0.94}]
這是一個最短路徑問題。 例如,如果您使用dijkstra_shortest_paths
則您要查找的結果將在distance_map
。 只需從該地圖中選擇“終止頂點”即可:
//#include <boost/spirit/home/x3.hpp>
#include <boost/graph/adjacency_list.hpp>
using Weight = double;
struct EdgeProps { Weight weight = 0; };
using Graph = boost::adjacency_list<
boost::vecS, boost::vecS, boost::directedS, boost::no_property, EdgeProps>;
Graph make_sample();
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/graph_utility.hpp>
int main() {
auto const g = make_sample();
auto const start = vertex(4, g);
print_graph(g);
// property-maps maps for dijkstra:
auto constexpr INF = std::numeric_limits<Weight>::infinity();
std::vector<Graph::vertex_descriptor> pred(num_vertices(g));
std::vector<Weight> dist(num_vertices(g), INF);
dijkstra_shortest_paths(g, start, boost::predecessor_map(pred.data())
.distance_map(dist.data())
.weight_map(get(&EdgeProps::weight, g))
.distance_inf(INF));
// print results
std::cout << "Final Result : [ ";
for (auto vd : boost::make_iterator_range(vertices(g))) {
if (INF != dist[vd] && 0 == out_degree(vd, g)) { // if reachable and leaf,
std::cout << "{" << vd << ", " << dist[vd] << "}, "; // print total distance from start
}
}
std::cout << "}\n";
}
Graph make_sample() {
Graph g(8);
add_edge(4, 1, EdgeProps{0.25}, g); // : T
add_edge(4, 5, EdgeProps{0.45}, g);
add_edge(4, 6, EdgeProps{0.5}, g);
add_edge(5, 2, EdgeProps{0.65}, g); // : T
add_edge(6, 3, EdgeProps{0.18}, g);
add_edge(6, 7, EdgeProps{0.44}, g); // : T
add_edge(3, 1, EdgeProps{0.33}, g); // : T
return g;
}
印刷
0 -->
1 -->
2 -->
3 --> 1
4 --> 1 5 6
5 --> 2
6 --> 3 7
7 -->
Final Result : [ {1, 0.25}, {2, 1.1}, {7, 0.94}, }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.