【问题标题】:strangeness in the work of the Bellman-ford algorithmBellman-ford 算法工作中的奇异之处
【发布时间】:2018-06-04 11:05:35
【问题描述】:

如果指定 -log () 权重显示“负循环”,我无法理解有什么问题。如果remove log(),算法有效,但是没有负循环

int main() {
    typedef double Weight;
    typedef property<edge_weight_t, Weight> WeightProperty;
    typedef property<vertex_name_t, string> NameProperty;
    typedef adjacency_list < listS, vecS, directedS, NameProperty, WeightProperty > Graph;
    typedef property_map < Graph, vertex_index_t >::type IndexMap;
    typedef property_map < Graph, vertex_name_t >::type NameMap;
    typedef graph_traits < Graph >::vertex_descriptor Vertex;
    typedef iterator_property_map < Vertex*, IndexMap, Vertex, Vertex& > PredecessorMap;
    typedef iterator_property_map < Weight*, IndexMap, Weight, Weight& > DistanceMap;

    // Create a graph
    Graph g;    
    graph_traits<Graph>::vertex_descriptor A = add_vertex(string("A"),g);
    graph_traits<Graph>::vertex_descriptor B = add_vertex(string("B"),g);
    graph_traits<Graph>::vertex_descriptor C = add_vertex(string("C"),g);
    graph_traits<Graph>::vertex_descriptor D = add_vertex(string("D"),g);
    add_edge(A, B, -log(0.741), g);
    add_edge(A, C, -log(0.657), g);
    add_edge(A, D, -log(1.061), g);
    add_edge(B, A, -log(1.350), g);
    add_edge(B, C, -log(0.888), g);
    add_edge(B, D, -log(1.433), g);
    add_edge(C, A, -log(1.521), g);
    add_edge(C, B, -log(1.126), g);
    add_edge(C, D, -log(1.614), g);
    add_edge(D, A, -log(0.943), g);
    add_edge(D, B, -log(0.698), g);
    add_edge(D, C, -log(0.620), g);

    property_map<Graph, edge_weight_t>::type weight_pmap = get(edge_weight_t(), g);

    int nb_vertices = num_vertices(g);
    int  inf = (numeric_limits<int>::max)();
    vector<float> distance(nb_vertices, inf);
    vector<size_t> parent(nb_vertices);
    for (size_t i = 0; i<nb_vertices; ++i)
        parent[i] = i;
    //starting vertex
    distance[B] = 0;

    //bool r = bellman_ford_shortest_paths(g, nb_vertices, weight_pmap, &parent[0], &distance[0],closed_plus<int>(), std::less<int>(), default_bellman_visitor());
    bool r = bellman_ford_shortest_paths(g, nb_vertices, weight_map(weight_pmap).distance_map(&distance[0]).predecessor_map(&parent[0]));

    if (r)
        for (size_t i = 1; i<nb_vertices; ++i)
            cout << distance[i]  << endl;
    else
        cout << "negative cycle" << endl;
    return EXIT_SUCCESS;
}

谁了解算法。告诉我我的错误在哪里?

【问题讨论】:

    标签: c++ boost boost-graph bellman-ford


    【解决方案1】:

    -log 惩罚函数通常用于独立概率,根据定义,它小于 1.0。

    -log(number_greater_than_one) =negative_number,因此您的路径得分为负。

    【讨论】:

    • 可以理解。我无法理解如何更改代码以使 Bellman-Ford 工作。图表中的权重,这是货币的价格。
    【解决方案2】:

    如果存在负循环,那么根据定义,您可以使任何连接的路径无限负成本(只是无限循环通过循环)。这是一个错误条件。

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2020-03-23
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多