Bellman-ford算法的工作中的陌生感

问题描述 投票:-4回答:2

如果指定-log()权重显示“负循环”,我无法理解什么是错误的。如果删除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
2个回答
1
投票

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.