2

我想使用 petgraph crate 中的 Bellman-Ford 算法。这是一个非常简单的示例程序,它不能编译:

extern crate petgraph;

use petgraph::prelude::*;
use petgraph::dot::{Dot, Config};
use petgraph::algo::bellman_ford;

fn main() {
    println!("Hello, world!");

    let mut deps = Graph::<&str, u64>::new();
    let a = deps.add_node("later");
    let b = deps.add_node("hello");
    deps.update_edge(a, b, 5);
    deps.update_edge(b, a, 10);

    let result = bellman_ford(deps, NodeIndex::new(0));
}

当我编译这个程序时,我得到这个错误信息:

error[E0277]: the trait bound `petgraph::Graph<&str, f64>: petgraph::visit::IntoNodeIdentifiers` is not satisfied
  --> src/main.rs:16:18
   |
16 |     let result = bellman_ford(deps, NodeIndex::new(0));
   |                  ^^^^^^^^^^^^ the trait `petgraph::visit::IntoNodeIdentifiers` is not implemented for `petgraph::Graph<&str, f64>`
   |
   = help: the following implementations were found:
             <&'a petgraph::Graph<N, E, Ty, Ix> as petgraph::visit::IntoNodeIdentifiers>
   = note: required by `petgraph::algo::bellman_ford`

error[E0277]: the trait bound `petgraph::Graph<&str, f64>: petgraph::visit::IntoEdges` is not satisfied
  --> src/main.rs:16:18
   |
16 |     let result = bellman_ford(deps, NodeIndex::new(0));
   |                  ^^^^^^^^^^^^ the trait `petgraph::visit::IntoEdges` is not implemented for `petgraph::Graph<&str, f64>`
   |
   = help: the following implementations were found:
             <&'a petgraph::Graph<N, E, Ty, Ix> as petgraph::visit::IntoEdges>
   = note: required by `petgraph::algo::bellman_ford`
4

1 回答 1

2

从我收集到的信息来看,实现的 Bellman-Ford 算法适用于浮点数,而不是整数。

使用浮点数而不是稍后u64引用就可以了:deps

use petgraph::algo::bellman_ford;

fn main() {
    let mut deps = Graph::<&str, f64>::new();
    let a = deps.add_node("later");
    let b = deps.add_node("hello");
    deps.update_edge(a, b, 5.0);
    deps.update_edge(b, a, 10.0);

    let result = bellman_ford(&deps, NodeIndex::new(0));
    println!("{:?}", result);
}
于 2017-05-24T22:30:35.143 回答