Skip to content

Commit

Permalink
remove par (#101)
Browse files Browse the repository at this point in the history
* remove par

* fix

---------

Co-authored-by: Luke Videckis <[email protected]>
  • Loading branch information
lrvideckis and lrvideckis authored Jul 27, 2024
1 parent 7670e46 commit d455276
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 25 deletions.
4 changes: 1 addition & 3 deletions examples/graphs/dijk_aizu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ fn main() {
adj[u].push((v, w));
}

let (dist, par) = dijk(&adj, s);

assert_eq!(par[s], None);
let dist = dijk(&adj, s);

for d in dist {
if d == u64::MAX {
Expand Down
30 changes: 22 additions & 8 deletions examples/graphs/dijk_yosupo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,35 @@ fn main() {
adj[u].push((v, w));
}

let (dist, par) = dijk(&adj, s);

assert_eq!(par[s], None);
let dist = dijk(&adj, s);

if dist[t] == u64::MAX {
println!("{}", -1);
return;
}

let mut path = vec![];
let mut par = vec![None; n];
{
let mut seen = vec![false; n];
seen[s] = true;
let mut q = std::collections::VecDeque::new();
q.push_back(s);
while let Some(u) = q.pop_front() {
for &(v, w) in &adj[u] {
if seen[v] || dist[u] + w != dist[v] {
continue;
}
par[v] = Some(u);
seen[v] = true;
q.push_back(v);
}
}
}
let mut path = vec![t];
let mut u = t;
path.push(u);
while let Some(prev_u) = par[u] {
path.push(prev_u);
u = prev_u;
while let Some(v) = par[u] {
u = v;
path.push(u);
}

path.reverse();
Expand Down
21 changes: 7 additions & 14 deletions src/graphs/dijk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,29 @@
/// adj[u].push((v, w));
/// }
///
/// let (dist, par) = dijk(&adj, 0);
/// let dist = dijk(&adj, 0);
/// assert_eq!(dist, [0, 10, 110, u64::MAX]);
/// assert_eq!(par, [None, Some(0), Some(1), None]);
///
/// let mut u = 2; // loop over shortest path in reverse
/// while let Some(prev) = par[u] {
/// u = prev;
/// }
/// ```
///
/// # Complexity
/// - V: number of vertices
/// - E: number of edges
/// - Time: O(V + E log E)
/// - Space: O(V + E)
pub fn dijk(adj: &[Vec<(usize, u64)>], s: usize) -> (Vec<u64>, Vec<Option<usize>>) {
pub fn dijk(adj: &[Vec<(usize, u64)>], s: usize) -> Vec<u64> {
use std::cmp::Reverse;
let n = adj.len();
let mut dist = vec![u64::MAX; n];
let mut par = vec![None; n];
let mut q = std::collections::BinaryHeap::new();
q.push(Reverse((0, s, None)));
while let Some(Reverse((d, u, p))) = q.pop() {
q.push(Reverse((0, s)));
while let Some(Reverse((d, u))) = q.pop() {
if dist[u] <= d {
continue;
}
(dist[u], par[u]) = (d, p);
dist[u] = d;
for &(v, w) in &adj[u] {
q.push(Reverse((dist[u] + w, v, Some(u))));
q.push(Reverse((dist[u] + w, v)));
}
}
(dist, par)
dist
}

0 comments on commit d455276

Please sign in to comment.