@@ -11,12 +11,12 @@ enum NodeState {
11
11
}
12
12
13
13
#[ derive( Copy , Clone , Eq , PartialEq ) ]
14
- struct State {
15
- cost : usize ,
14
+ struct NodeCost {
15
+ cost : i32 ,
16
16
node : usize ,
17
17
}
18
18
19
- impl Ord for State {
19
+ impl Ord for NodeCost {
20
20
fn cmp ( & self , other : & Self ) -> Ordering {
21
21
// maxヒープをminヒープとして使用するためには,
22
22
// コストがより小さい方がGreaterとなるよう順序を反転する
@@ -26,30 +26,41 @@ impl Ord for State {
26
26
. then_with ( || self . node . cmp ( & other. node ) )
27
27
}
28
28
}
29
- impl PartialOrd for State {
29
+ impl PartialOrd for NodeCost {
30
30
fn partial_cmp ( & self , other : & Self ) -> Option < Ordering > {
31
31
Some ( self . cmp ( other) )
32
32
}
33
33
}
34
34
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 > {
38
36
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] ;
40
39
41
40
// start from node 0
41
+ cost_calc_heap. push ( NodeCost { cost : 0 , node : 0 } ) ;
42
42
cost_from_start[ 0 ] = 0 ;
43
43
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 ; }
47
49
48
- for
50
+ node_state [ path_resolved_node . node ] = NodeState :: Finished ;
49
51
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
+ }
50
59
}
60
+ cost_from_start
51
61
}
52
- */
62
+
63
+
53
64
fn main ( ) {
54
65
55
66
let node_count: usize = input:: read_number ( ) ;
@@ -64,11 +75,10 @@ fn main() {
64
75
graph[ node] . push ( ( node_to, path_cost) ) ;
65
76
}
66
77
}
67
- /*
78
+
68
79
let cost_from_start = dikkstra ( node_count, & mut graph) ;
69
80
for ( node, cost) in cost_from_start. iter ( ) . enumerate ( ) {
70
81
println ! ( "{} {}" , node, cost) ;
71
82
}
72
- */
73
83
74
84
}
0 commit comments