Skip to content

Commit 999a1db

Browse files
committed
fisished chapter 13
1 parent 460aeed commit 999a1db

File tree

1 file changed

+25
-15
lines changed
  • chapter_13/shortest_path_2/src

1 file changed

+25
-15
lines changed

chapter_13/shortest_path_2/src/main.rs

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ enum NodeState {
1111
}
1212

1313
#[derive(Copy, Clone, Eq, PartialEq)]
14-
struct State {
15-
cost: usize,
14+
struct NodeCost {
15+
cost: i32,
1616
node: usize,
1717
}
1818

19-
impl Ord for State {
19+
impl Ord for NodeCost {
2020
fn cmp(&self, other: &Self) -> Ordering {
2121
// maxヒープをminヒープとして使用するためには,
2222
// コストがより小さい方がGreaterとなるよう順序を反転する
@@ -26,30 +26,41 @@ impl Ord for State {
2626
.then_with(|| self.node.cmp(&other.node))
2727
}
2828
}
29-
impl PartialOrd for State {
29+
impl PartialOrd for NodeCost {
3030
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3131
Some(self.cmp(other))
3232
}
3333
}
3434

35-
/*
36-
37-
fn dikkstra(node_count: usize, graph: &mut Vec<Vec<(usize, i32)>>) {
35+
fn dikkstra(node_count: usize, graph: &mut Vec<Vec<(usize, i32)>>) -> Vec<i32> {
3836
let mut node_state: Vec<NodeState> = vec![NodeState::UnReached; node_count];
39-
let mut cost_from_start :BinaryHeap<(usize, i32)> = BinaryHeap::new();
37+
let mut cost_calc_heap :BinaryHeap<NodeCost> = BinaryHeap::new();
38+
let mut cost_from_start: Vec<i32> = vec![i32::MAX; node_count];
4039

4140
// start from node 0
41+
cost_calc_heap.push(NodeCost{cost: 0, node:0});
4242
cost_from_start[0] = 0;
4343

44-
loop {
45-
let mut cost_to_node = i32::MAX;
46-
let mut is_unfinished_node_found = false;
44+
while !cost_calc_heap.is_empty() {
45+
let path_resolved_node = cost_calc_heap.pop().unwrap();
46+
47+
// already found better path
48+
if path_resolved_node.cost > cost_from_start[path_resolved_node.node] { continue; }
4749

48-
for
50+
node_state[path_resolved_node.node] = NodeState::Finished;
4951

52+
for cost_to_node in &graph[path_resolved_node.node] {
53+
if cost_from_start[cost_to_node.0] > cost_from_start[path_resolved_node.node] + cost_to_node.1 {
54+
cost_from_start[cost_to_node.0] = cost_from_start[path_resolved_node.node] + cost_to_node.1;
55+
node_state[cost_to_node.0] = NodeState::Reached;
56+
cost_calc_heap.push(NodeCost{cost: cost_from_start[cost_to_node.0] , node:cost_to_node.0})
57+
}
58+
}
5059
}
60+
cost_from_start
5161
}
52-
*/
62+
63+
5364
fn main() {
5465

5566
let node_count: usize = input::read_number();
@@ -64,11 +75,10 @@ fn main() {
6475
graph[node].push((node_to, path_cost));
6576
}
6677
}
67-
/*
78+
6879
let cost_from_start = dikkstra(node_count, &mut graph);
6980
for (node, cost) in cost_from_start.iter().enumerate() {
7081
println!("{} {}", node, cost);
7182
}
72-
*/
7383

7484
}

0 commit comments

Comments
 (0)