algs4 0.7.0

Algorithms, 4ed. MOOC in Coursera. in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
use std::fmt;
use std::iter;
use std::f64;

use adivon::bag::Bag;
use adivon::stack::Stack;
use adivon::queue::Queue;
use adivon::priority_queue::IndexMinPQ;

/// Weighted directed edge
#[derive(Clone, Copy)]
pub struct DirectedEdge {
    v: usize,
    w: usize,
    weight: f64
}

impl DirectedEdge {
    pub fn new(v: usize, w: usize, weight: f64) -> DirectedEdge {
        assert!(!weight.is_nan(), "weight is NaN");
        DirectedEdge {
            v: v,
            w: w,
            weight: weight
        }
    }

    #[inline]
    pub fn from(&self) -> usize {
        self.v
    }

    #[inline]
    pub fn to(&self) -> usize {
        self.w
    }

    #[inline]
    pub fn weight(&self) -> f64 {
        self.weight
    }
}

impl fmt::Debug for DirectedEdge {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} -> {} {:5.2}", self.v, self.w, self.weight)
    }
}

#[test]
fn test_directed_edge() {
    let e = DirectedEdge::new(12, 24, 3.14);
    assert_eq!(format!("{:?}", e), "12 -> 24  3.14");
}


/// Edge-weighted digraph, implemented using adjacency lists
#[derive(Clone)]
pub struct EdgeWeightedDigraph {
    v: usize,
    e: usize,
    adj: Vec<Bag<DirectedEdge>>
}

impl EdgeWeightedDigraph {
    pub fn new(v: usize) -> EdgeWeightedDigraph {
        EdgeWeightedDigraph {
            v: v,
            e: 0,
            adj: iter::repeat(Bag::new()).take(v).collect()
        }
    }

    pub fn v(&self) -> usize {
        self.v
    }

    pub fn e(&self) -> usize {
        self.e
    }

    #[inline]
    fn validate_vertex(&self, v: usize) {
        assert!(v < self.v, "vertex must be between 0 and V");
    }

    pub fn add_edge(&mut self, e: DirectedEdge) {
        let v = e.from();
        let w = e.to();
        self.validate_vertex(v);
        self.validate_vertex(w);
        self.adj[v].add(e);
        self.e += 1;
    }

    pub fn adj(&self, v: usize) -> ::std::vec::IntoIter<DirectedEdge> {
        self.validate_vertex(v);
        self.adj[v].iter().map(|e| e.clone()).collect::<Vec<DirectedEdge>>().into_iter()
    }

    pub fn outdegree(&self, v: usize) -> usize {
        self.validate_vertex(v);
        self.adj[v].len()
    }

    pub fn edges(&self) -> ::std::vec::IntoIter<DirectedEdge> {
        self.adj.iter()
            .flat_map(|adj| {
                adj.iter().map(|e| e.clone()).collect::<Vec<DirectedEdge>>().into_iter()
            })
            .collect::<Vec<DirectedEdge>>()
            .into_iter()
    }

    pub fn to_dot(&self) -> String {
        let mut dot = String::new();

        dot.push_str("digraph G {\n");
        for i in 0 .. self.v {
            dot.push_str(&format!("  {};\n", i));
        }

        for e in self.edges() {
            let v = e.from();
            let w = e.to();
            dot.push_str(&format!("  {} -> {} [ label=\"{}\" ];\n",
                                  v, w, e.weight))
        }
        dot.push_str("}\n");
        dot
    }
}


// Single-source shortest paths API
#[allow(dead_code)]
pub struct DijkstraSP<'a> {
    graph: &'a EdgeWeightedDigraph,
    dist_to: Vec<f64>,
    edge_to: Vec<Option<DirectedEdge>>,
    pq: IndexMinPQ<f64>,
    s: usize
}

impl<'a> DijkstraSP<'a> {
    fn new<'b>(graph: &'b EdgeWeightedDigraph, s: usize) -> DijkstraSP<'b> {
        let n = graph.v();
        for e in graph.edges() {
            if e.weight() < 0.0 {
                panic!("edge has negative weight in DijkstraSP");
            }
        }
        let dist_to = iter::repeat(f64::INFINITY).take(n).collect();
        let edge_to = iter::repeat(None).take(n).collect();
        let pq = IndexMinPQ::with_capacity(n);
        let mut sp = DijkstraSP {
            graph: graph,
            s: s,
            dist_to: dist_to,
            edge_to: edge_to,
            pq: pq
        };
        // alogrithm
        sp.dist_to[s] = 0.0;

        sp.pq.insert(s, 0.0);
        while !sp.pq.is_empty() {
            let v = sp.pq.del_min().unwrap();
            for e in graph.adj(v) {
                sp.relax(e);
            }
        }

        sp
    }

    fn relax(&mut self, e: DirectedEdge) {
        let v = e.from();
        let w = e.to();
        if self.dist_to[w] > self.dist_to[v] + e.weight() {
            self.dist_to[w] = self.dist_to[v] + e.weight();
            self.edge_to[w] = Some(e);
            if self.pq.contains(w) {
                self.pq.decrease_key(w, self.dist_to[w]);
            } else {
                self.pq.insert(w, self.dist_to[w]);
            }
        }
    }

    // length of shortest path from s to v
    pub fn dist_to(&self, v: usize) -> f64 {
        self.dist_to[v]
    }

    pub fn has_path_to(&self, v: usize) -> bool {
        self.dist_to[v] < f64::INFINITY
    }

    // shortest path from s to v
    pub fn path_to(&self, v: usize) -> ::std::vec::IntoIter<DirectedEdge> {
        if !self.has_path_to(v) {
            vec!().into_iter()
        } else {
            let mut path = Stack::new();
            let mut e = self.edge_to[v];
            while e.is_some() {
                path.push(e.unwrap());
                e = self.edge_to[e.unwrap().from()]
            }
            path.into_iter().collect::<Vec<DirectedEdge>>().into_iter()
        }
    }

    #[cfg(test)]
    fn check(&self) -> bool {
        let s = self.s;
        for e in self.graph.edges() {
            if e.weight() < 0.0 {
                return false;
            }
        }

        if self.dist_to[s] != 0.0 || self.edge_to[s].is_some() {
            return false;
        }

        for v in 0 .. self.graph.v() {
            if v == s { continue }
            if self.edge_to[v].is_none() && self.dist_to[v] != f64::INFINITY {
                // dist_to[] edge_to[] inconsistent
                return false;
            }
        }

        for v in 0 .. self.graph.v() {
            for e in self.graph.adj(v) {
                let w  = e.to();
                if self.dist_to[v] + e.weight() < self.dist_to[w] {
                    // edge not relaxed
                    return false;
                }
            }
        }

        for w in 0 .. self.graph.v() {
            if self.edge_to[w].is_none() { continue }
            let e = self.edge_to[w].unwrap();
            let v = e.from();
            if w != e.to() {
                return false;
            }
            if self.dist_to[v] + e.weight() != self.dist_to[w] {
                // edge on shortest path not tight
                return false;
            }
        }

        true
    }
}

/// Compute preorder and postorder for a digraph or edge-weighted digraph
pub struct DepthFirstOrder<'a> {
    graph: &'a EdgeWeightedDigraph,
    pre: Vec<usize>,
    post: Vec<usize>,
    preorder: Queue<usize>,
    postorder: Queue<usize>,
    marked: Vec<bool>,
    pre_counter: usize,
    post_counter: usize
}

impl<'a> DepthFirstOrder<'a> {
    fn new<'b>(graph: &'b EdgeWeightedDigraph) -> DepthFirstOrder<'b> {
        let n = graph.v();
        let mut ret = DepthFirstOrder {
            graph: graph,
            pre: iter::repeat(0).take(n).collect(),
            post: iter::repeat(0).take(n).collect(),
            preorder: Queue::new(),
            postorder: Queue::new(),
            marked: iter::repeat(false).take(n).collect(),
            pre_counter: 0,
            post_counter: 0
        };
        ret.init();
        ret
    }

    fn init(&mut self) {
        for v in 0 .. self.graph.v() {
            if !self.marked[v] {
                self.dfs(v)
            }
        }
    }

    fn dfs(&mut self, v: usize) {
        self.marked[v] = true;
        self.pre[v] = self.pre_counter;
        self.pre_counter += 1;
        self.preorder.enqueue(v);
        for e in self.graph.adj(v) {
            let w = e.to();
            if !self.marked[w] {
                self.dfs(w);
            }
        }
        self.postorder.enqueue(v);
        self.post[v] = self.post_counter;
        self.post_counter += 1;
    }

    // preorder number of vertex v
    pub fn preorder(&self, v: usize) -> usize {
        self.pre[v]
    }

    // postorder number of vertex v
    pub fn postorder(&self, v: usize) -> usize {
        self.post[v]
    }

    pub fn pre(&self) -> ::std::vec::IntoIter<usize> {
        self.preorder.clone().into_iter().collect::<Vec<usize>>().into_iter()
    }

    pub fn post(&self) -> ::std::vec::IntoIter<usize> {
        self.postorder.clone().into_iter().collect::<Vec<usize>>().into_iter()
    }

    pub fn reverse_post(&self) -> ::std::vec::IntoIter<usize> {
        let mut reverse = Stack::new();
        for v in self.postorder.iter() {
            reverse.push(*v);
        }
        reverse.into_iter().collect::<Vec<usize>>().into_iter()
    }

    #[cfg(test)]
    fn check(&self) -> bool {
        let mut r = 0;
        for v in self.post() {
            if self.postorder(v) != r {
                // post(v) and post() inconsistent
                return false;
            }
            r += 1;
        }

        r = 0;
        for v in self.pre() {
            if self.preorder(v) != r {
                // preorder(v) and pre() inconsistent
                return false;
            }
            r += 1;
        }
        return true;
    }
}


// Finds a directed cycle in an edge-weighted digraph
pub struct EdgeWeightedDirectedCycle<'a> {
    graph: &'a EdgeWeightedDigraph,
    marked: Vec<bool>,
    edge_to: Vec<Option<DirectedEdge>>,
    on_stack: Vec<bool>,
    // directed cycle (or empty)
    cycle: Option<Stack<DirectedEdge>>
}

impl<'a> EdgeWeightedDirectedCycle<'a> {
    fn new<'b>(graph: &'b EdgeWeightedDigraph) -> EdgeWeightedDirectedCycle<'b> {
        let n = graph.v();
        let mut ret = EdgeWeightedDirectedCycle {
            graph: graph,
            marked: iter::repeat(false).take(n).collect(),
            edge_to: iter::repeat(None).take(n).collect(),
            on_stack: iter::repeat(false).take(n).collect(),
            cycle: None
        };
        ret.init();
        ret
    }

    fn init(&mut self) {
        for v in 0 .. self.graph.v() {
            if !self.marked[v] {
                self.dfs(v)
            }
        }
    }

    fn dfs(&mut self, v: usize) {
        self.on_stack[v] = true;
        self.marked[v] = true;
        for e in self.graph.adj(v) {
            let w = e.to();

            if self.cycle.is_some() {
                return;
            } else if !self.marked[w] {
                self.edge_to[w] = Some(e);
                self.dfs(w);
            } else if self.on_stack[w] {
                self.cycle = Some(Stack::new());
                // scope local
                let mut e = e.clone();
                while e.from() != w {
                    self.cycle.as_mut().map(|s| s.push(e));
                    e = self.edge_to[e.from()].unwrap();
                }
                self.cycle.as_mut().map(|s| s.push(e));
            }
        }
        self.on_stack[v] = false;
    }

    pub fn has_cycle(&self) -> bool {
        self.cycle.is_some()
    }

    pub fn edges(&self) -> ::std::vec::IntoIter<DirectedEdge> {
        self.cycle.iter().flat_map(|e| e.clone()).collect::<Vec<DirectedEdge>>().into_iter()
    }

    #[cfg(test)]
    fn check(&self) -> bool {
        if self.has_cycle() {
            let first = self.edges().next().unwrap();
            let last = self.edges().last().unwrap();

            if first.from() == last.to() {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }
}

/// Compute topological ordering of a DAG or edge-weighted DAG
pub enum Topological {
    NonDAG,
    Order(Vec<usize>)
}

impl Topological {
    fn new(graph: &EdgeWeightedDigraph) -> Topological {
        if graph.cycle().has_cycle() {
            Topological::NonDAG
        } else {
            Topological::Order(graph.depth_first_order().reverse_post().collect())
        }
    }

    pub fn order(&self) -> ::std::vec::IntoIter<usize> {
        match self {
            &Topological::Order(ref order) => {
                order.clone().into_iter()
            },
            &Topological::NonDAG => {
                vec![].into_iter()
            }
        }
    }

    pub fn has_order(&self) -> bool {
        match self {
            &Topological::NonDAG    => false,
            &Topological::Order(_)  => true
        }
    }
}

// Computes shortest paths in an edge-weighted acyclic digraph
pub struct AcyclicSP<'a> {
    graph: &'a EdgeWeightedDigraph,
    dist_to: Vec<f64>,
    edge_to: Vec<Option<DirectedEdge>>
}

impl<'a> AcyclicSP<'a> {
    fn new<'b>(graph: &'b EdgeWeightedDigraph, s: usize) -> AcyclicSP<'b> {
        let n = graph.v();
        let dist_to: Vec<f64> = iter::repeat(f64::INFINITY).take(n).collect();
        let edge_to = iter::repeat(None).take(n).collect();

        let mut ret = AcyclicSP {
            graph: graph,
            dist_to: dist_to,
            edge_to: edge_to
        };

        ret.dist_to[s] = 0.0;

        let topological = ret.graph.topological();
        if !topological.has_order() {
            panic!("digraph is not acyclic");
        }

        for v in topological.order() {
            for e in ret.graph.adj(v) {
                ret.relax(e);
            }
        }
        ret
    }

    fn relax(&mut self, e: DirectedEdge) {
        let v = e.from();
        let w = e.to();
        if self.dist_to[w] > self.dist_to[v] + e.weight() {
            self.dist_to[w] = self.dist_to[v] + e.weight();
            self.edge_to[w] = Some(e);
        }
    }

    pub fn dist_to(&self, v: usize) -> f64 {
        self.dist_to[v]
    }

    pub fn has_path_to(&self, v: usize) -> bool {
        self.dist_to[v] < f64::INFINITY
    }

    pub fn path_to(&self, v: usize) -> ::std::vec::IntoIter<DirectedEdge> {
        if !self.has_path_to(v) {
            vec![].into_iter()
        } else {
            let mut path = Stack::new();
            let mut e = self.edge_to[v];
            while e.is_some() {
                path.push(e.unwrap());
                e = self.edge_to[e.unwrap().from()];
            }
            path.into_iter().collect::<Vec<DirectedEdge>>().into_iter()
        }
    }
}


/// Bellman-Ford shortest path algorithm. Computes the shortest path tree in
/// edge-weighted digraph G from vertex s, or finds a negative cost cycle
/// reachable from s.
pub struct BellmanFordSP<'a> {
    graph: &'a EdgeWeightedDigraph,
    dist_to: Vec<f64>,
    edge_to: Vec<Option<DirectedEdge>>,
    on_queue: Vec<bool>,
    queue: Queue<usize>,
    cost: usize,
    cycle: Option<Vec<DirectedEdge>>
}

impl<'a> BellmanFordSP<'a> {
    fn new<'b>(graph: &'b EdgeWeightedDigraph, s: usize) -> BellmanFordSP<'b> {
        let n = graph.v();
        let dist_to = iter::repeat(f64::INFINITY).take(n).collect();
        let edge_to = iter::repeat(None).take(n).collect();
        let on_queue = iter::repeat(false).take(n).collect();

        let mut ret = BellmanFordSP {
            graph: graph,
            dist_to: dist_to,
            edge_to: edge_to,
            on_queue: on_queue,
            queue: Queue::new(),
            cost: 0,
            cycle: None
        };

        ret.dist_to[s] = 0.0;

        // Bellman-Ford algorithm
        ret.queue.enqueue(s);
        ret.on_queue[s] = true;
        while !ret.queue.is_empty() && !ret.has_negative_cycle() {
            let v = ret.queue.dequeue().unwrap();
            ret.on_queue[v] = false;
            ret.relax(v);
        }

        ret
    }

    fn relax(&mut self, v: usize) {
        for e in self.graph.adj(v) {
            let w = e.to();
            if self.dist_to[w] > self.dist_to[v] + e.weight() {
                self.dist_to[w] = self.dist_to[v] + e.weight();
                self.edge_to[w] = Some(e);
                if !self.on_queue[w] {
                    self.queue.enqueue(w);
                    self.on_queue[w] = true;
                }
            }
            // workaround
            self.cost += 1;
            if (self.cost - 1) % self.graph.v() == 0 {
                self.find_negative_cycle();
                if self.has_negative_cycle() {
                    return;
                }
            }
        }
    }

    pub fn has_negative_cycle(&self) -> bool {
        self.cycle.is_some()
    }

    pub fn negative_cycle(&self) -> ::std::vec::IntoIter<DirectedEdge> {
        self.cycle.iter().flat_map(|e| e.clone()).collect::<Vec<DirectedEdge>>().into_iter()
    }

    fn find_negative_cycle(&mut self) {
        let n = self.graph.v();
        let mut spt = EdgeWeightedDigraph::new(n);
        for v in 0 .. n {
            if self.edge_to[v].is_some() {
                spt.add_edge(self.edge_to[v].unwrap());
            }
        }

        let finder = spt.cycle();
        if finder.has_cycle() {
            self.cycle = Some(finder.edges().collect());
        } else {
            self.cycle = None;
        }
    }

    pub fn dist_to(&self, v: usize) -> f64 {
        if self.has_negative_cycle() {
            panic!("negative cost cycle exists")
        } else {
            self.dist_to[v]
        }
    }

    pub fn has_path_to(&self, v: usize) -> bool {
        self.dist_to[v] < f64::INFINITY
    }

    pub fn path_to(&self, v: usize) -> ::std::vec::IntoIter<DirectedEdge> {
        if self.has_negative_cycle() {
            panic!("negative cost cycle exists")
        } else if !self.has_path_to(v) {
            vec![].into_iter()
        } else {
            let mut path = Stack::new();
            let mut e = self.edge_to[v];
            while e.is_some() {
                path.push(e.unwrap());
                e = self.edge_to[e.unwrap().from()];
            }
            path.into_iter().collect::<Vec<DirectedEdge>>().into_iter()
        }
    }
}

impl EdgeWeightedDigraph {
    /// Compute preorder and postorder for a digraph or edge-weighted digraph.
    pub fn depth_first_order<'a>(&'a self) -> DepthFirstOrder<'a> {
        DepthFirstOrder::new(self)
    }

    /// Dijkstra's algorithm. Computes the shortest path tree.
    pub fn dijkstra_sp<'a>(&'a self, s: usize) -> DijkstraSP<'a> {
        DijkstraSP::new(self, s)
    }

    /// Finds a directed cycle in an edge-weighted digraph.
    pub fn cycle<'a>(&'a self) -> EdgeWeightedDirectedCycle<'a> {
        EdgeWeightedDirectedCycle::new(self)
    }

    /// Compute topological ordering of a DAG or edge-weighted DAG.
    pub fn topological(&self) -> Topological {
        Topological::new(self)
    }

    /// Computes shortest paths in an edge-weighted acyclic digraph.
    pub fn acyclic_sp<'a>(&'a self, s: usize) -> AcyclicSP<'a> {
        AcyclicSP::new(self, s)
    }

    /// Bellman-Ford shortest path algorithm.
    pub fn bellman_ford_sp<'a>(&'a self, s: usize) -> BellmanFordSP<'a> {
        BellmanFordSP::new(self, s)
    }
}


#[test]
fn test_dijkstra_shortest_path() {
    let mut g = EdgeWeightedDigraph::new(6);
    g.add_edge(DirectedEdge::new(0, 1, 7.0));
    g.add_edge(DirectedEdge::new(1, 2, 10.0));
    g.add_edge(DirectedEdge::new(0, 2, 9.0));
    g.add_edge(DirectedEdge::new(0, 5, 14.0));
    g.add_edge(DirectedEdge::new(1, 3, 15.0));
    g.add_edge(DirectedEdge::new(2, 5, 2.0));
    g.add_edge(DirectedEdge::new(2, 3, 11.0));
    g.add_edge(DirectedEdge::new(4, 5, 9.0));
    g.add_edge(DirectedEdge::new(3, 4, 6.0));
    // this edge makes a non-DAG
    g.add_edge(DirectedEdge::new(2, 2, 1.0));

    assert_eq!(20.0, g.dijkstra_sp(0).dist_to(3));
    assert_eq!(26.0, g.dijkstra_sp(0).path_to(4).map(|e| e.weight()).sum());

    assert!(g.dijkstra_sp(0).check());
}


#[test]
fn test_cyclic_edge_weighted_directed_graph() {
    let mut g = EdgeWeightedDigraph::new(4);
    g.add_edge(DirectedEdge::new(0, 1, 0.5));
    g.add_edge(DirectedEdge::new(0, 2, 0.5));
    g.add_edge(DirectedEdge::new(1, 2, 0.5));
    g.add_edge(DirectedEdge::new(2, 3, 0.5));
    g.add_edge(DirectedEdge::new(3, 1, 0.5));

    let cycle = g.cycle();
    assert!(cycle.has_cycle());
    assert_eq!(3, cycle.edges().count());
    assert!(cycle.check());
}



#[test]
fn test_acyclic_shortest_path() {
    let mut g = EdgeWeightedDigraph::new(6);
    g.add_edge(DirectedEdge::new(0, 1, 7.0));
    g.add_edge(DirectedEdge::new(1, 2, 10.0));
    g.add_edge(DirectedEdge::new(0, 2, 9.0));
    g.add_edge(DirectedEdge::new(0, 5, 14.0));
    g.add_edge(DirectedEdge::new(1, 3, 15.0));
    g.add_edge(DirectedEdge::new(2, 5, 2.0));
    g.add_edge(DirectedEdge::new(2, 3, 11.0));
    g.add_edge(DirectedEdge::new(4, 5, 9.0));
    g.add_edge(DirectedEdge::new(3, 4, 6.0));

    assert!(g.depth_first_order().check());

    assert_eq!(20.0, g.acyclic_sp(0).dist_to(3));
    assert_eq!(26.0, g.acyclic_sp(0).path_to(4).map(|e| e.weight()).sum());
}

#[test]
fn test_negative_weight_shortest_path() {
    let mut g = EdgeWeightedDigraph::new(6);
    g.add_edge(DirectedEdge::new(0, 1, 7.0));
    g.add_edge(DirectedEdge::new(1, 2, 10.0));
    g.add_edge(DirectedEdge::new(0, 2, 9.0));
    g.add_edge(DirectedEdge::new(0, 5, 14.0));
    g.add_edge(DirectedEdge::new(1, 3, 15.0));
    g.add_edge(DirectedEdge::new(2, 5, 2.0));
    g.add_edge(DirectedEdge::new(2, 3, 11.0));
    g.add_edge(DirectedEdge::new(4, 5, 9.0));
    g.add_edge(DirectedEdge::new(3, 4, 6.0));

    assert_eq!(20.0, g.bellman_ford_sp(0).dist_to(3));
    assert_eq!(26.0, g.bellman_ford_sp(0).path_to(4).map(|e| e.weight()).sum());

    g.add_edge(DirectedEdge::new(0, 3, -5.0));

    assert_eq!(1.0, g.bellman_ford_sp(0).dist_to(4));
    assert_eq!(2, g.bellman_ford_sp(0).path_to(4).count());
    assert_eq!(1.0, g.bellman_ford_sp(0).path_to(4).map(|e| e.weight()).sum());
}