gpt4 book ai didi

algorithm - 使用 petgraph 中的 Bellman-Ford 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:47:32 25 4
gpt4 key购买 nike

我想使用 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`

最佳答案

根据我收集到的信息,已实现的 Bellman-Ford 算法适用于 float ,而不是整数。

使用 float 而不是 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);
}

关于algorithm - 使用 petgraph 中的 Bellman-Ford 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44165951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com