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
//! An implementation of the eager version of Prim's algorithm which relies on using an indexed
//! priority queue data structure to query the next best edge.
//!
//! # Resources
//!
//! - [W. Fiset's video 1](https://www.youtube.com/watch?v=jsmMtJpPnhU&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=30)
//! - [W. Fiset's video 2](https://www.youtube.com/watch?v=xq3ABa-px_g&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=31)
//! - [W. Fiset's video 3](https://www.youtube.com/watch?v=CI5Fvk-dGVs&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=32)
//! - [Wikipedia](https://www.wikiwand.com/en/Prim%27s_algorithm)

use crate::algo::graph::{Edge, WeightedAdjacencyList};
use ordered_float::OrderedFloat;
use priority_queue::PriorityQueue;

impl WeightedAdjacencyList {
    pub fn prim(&self) -> Option<(f32, WeightedAdjacencyList)> {
        let n = self.vertices_count();
        // the number of edges in the MST (a tree with `n` vertices has `n - 1` edges)
        let m = n - 1;

        let mut visited = vec![false; n];
        let mut pq = PriorityQueue::new();

        let add_edges = |from, visited: &mut [bool], pq: &mut PriorityQueue<_, _>| {
            visited[from] = true;
            // iterate over all edges going outwards from the current node.
            // Add edges to the PQ which point to unvisited nodes.
            for &Edge { to, cost } in &self[from] {
                if !visited[to] {
                    // `push_increase` queues an element if it's not already present.
                    // Otherwise, it updates the element's priority if the new priority is higher.
                    pq.push_increase((from, to), OrderedFloat(-cost));
                }
            }
        };

        let mut min_mst_cost = f32::INFINITY;
        let mut best_mst_edges = Vec::new();
        for i in 0..n {
            let mut mst_cost = 0.;
            let mut mst_edges = Vec::with_capacity(m);
            add_edges(i, &mut visited, &mut pq);

            while let Some(((from, to), cost)) = pq.pop() {
                if mst_edges.len() == m {
                    break;
                };
                if visited[to] {
                    continue;
                }
                mst_edges.push((from, to, -cost.into_inner()));
                mst_cost += -cost.into_inner();

                add_edges(to, &mut visited, &mut pq);
            }
            if mst_edges.len() != m {
                continue;
            }
            if mst_cost < min_mst_cost {
                min_mst_cost = mst_cost;
                best_mst_edges = mst_edges
            }
        }
        if min_mst_cost == f32::INFINITY {
            None
        } else {
            Some((
                min_mst_cost,
                WeightedAdjacencyList::new_directed(n, &best_mst_edges),
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_prim1() {
        // from https://www.youtube.com/watch?v=jsmMtJpPnhU&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=30
        // at 10:05
        let g = WeightedAdjacencyList::new_directed(
            8,
            &[
                (0, 1, 10.),
                (0, 2, 1.),
                (0, 3, 4.),
                (2, 1, 3.),
                (2, 5, 8.),
                (2, 3, 2.),
                (2, 0, 1.),
                (3, 2, 2.),
                (3, 5, 2.),
                (3, 6, 7.),
                (3, 0, 4.),
                (5, 2, 8.),
                (5, 4, 1.),
                (5, 7, 9.),
                (5, 6, 6.),
                (5, 3, 2.),
                (4, 1, 0.),
                (4, 5, 1.),
                (4, 7, 8.),
                (1, 0, 10.),
                (1, 2, 3.),
                (1, 4, 0.),
                (6, 3, 7.),
                (6, 5, 6.),
                (6, 7, 12.),
                (7, 4, 8.),
                (7, 5, 9.),
                (7, 6, 12.),
            ],
        );
        let (cost, mst) = g.prim().unwrap();
        println!("{}", mst);
        assert_eq!(cost, 20.);
    }
    #[test]
    fn test_prim2() {
        // from https://www.youtube.com/watch?v=xq3ABa-px_g&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=31
        // at 08:31
        let g = WeightedAdjacencyList::new_directed(
            7,
            &[
                (0, 2, 0.),
                (0, 5, 7.),
                (0, 3, 5.),
                (0, 1, 9.),
                (2, 0, 0.),
                (2, 5, 6.),
                (3, 0, 5.),
                (3, 1, -2.),
                (3, 6, 3.),
                (3, 5, 2.),
                (1, 0, 9.),
                (1, 3, -2.),
                (1, 6, 4.),
                (1, 4, 3.),
                (5, 2, 6.),
                (5, 0, 7.),
                (5, 3, 2.),
                (5, 6, 1.),
                (6, 5, 1.),
                (6, 3, 3.),
                (6, 1, 4.),
                (6, 4, 6.),
                (4, 1, 3.),
                (4, 6, 6.),
            ],
        );
        let (cost, mst) = g.prim().unwrap();
        println!("{}", mst);
        assert_eq!(cost, 9.);
    }
}