Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
indy256 committed May 23, 2021
1 parent 4eabda1 commit 5d51f25
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 2 deletions.
7 changes: 6 additions & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
name = "codelibrary"
version = "0.1.0"

edition = "2018"

[[bin]]
name = "test"
path = "src/euclid.rs"
path = "graphs/shortestpaths/dijkstra.rs"

[dependencies]
priority-queue = "1.1.1"
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
fn dfs(graph: &Vec<Vec<usize>>, used: &mut Vec::<bool>, order: &mut Vec::<usize>, u: usize) {
fn dfs(graph: &Vec<Vec<usize>>, used: &mut Vec<bool>, order: &mut Vec<usize>, u: usize) {
used[u] = true;
for v in &graph[u] {
if !used[*v] {
Expand Down
31 changes: 31 additions & 0 deletions rust/graphs/matchings/max_bipartite_matching_EV.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
fn find_path(graph: &Vec<Vec<usize>>, u1: usize, matching: &mut Vec<usize>, vis: &mut Vec<bool>) -> bool {
vis[u1] = true;
for v in &graph[u1] {
let u2 = matching[*v];
if u2 == usize::MAX || (!vis[u2] && find_path(graph, u2, matching, vis)) {
matching[*v] = u1;
return true;
}
}
return false;
}

pub fn max_matching(graph: &Vec<Vec<usize>>, n2: usize) -> (usize, Vec<usize>) {
let n1 = graph.len();
let mut matching = vec![usize::MAX; n2];
let mut matches = 0;
for u in 0..n1 {
let mut vis = vec![false; n1];
if find_path(graph, u, &mut matching, &mut vis) {
matches += 1;
}
}
return (matches, matching);
}

fn main() {
let g = vec![vec![0, 1], vec![0]];
let (cardinality, matching) = max_matching(&g, 2);
assert_eq!(cardinality, 2);
assert_eq!(matching, vec![1, 0]);
}
35 changes: 35 additions & 0 deletions rust/graphs/shortestpaths/dijkstra.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use priority_queue::PriorityQueue;

// https://cp-algorithms.com/graph/dijkstra_sparse.html
// O(E*log(V)) time and O(V) memory
pub fn dijkstra_heap(graph: &Vec<Vec<(usize, i32)>>, s: usize) -> (Vec<i32>, Vec<usize>) {
let n = graph.len();
let mut prio = vec![i32::MAX; n];
let mut pred = vec![usize::MAX; n];
let mut q = PriorityQueue::<usize, i32>::new();
prio[s] = 0;
q.push(0, 0);
loop {
match q.pop() {
None => break,
Some((u, _d)) => {
for (v, len) in &graph[u] {
let nprio = prio[u] + len;
if prio[*v] > nprio {
prio[*v] = nprio;
pred[*v] = u;
q.push(*v, nprio);
}
}
}
}
}
return (prio, pred);
}

fn main() {
let g = vec![vec![(1, 10), (2, 8)], vec![(2, -5)], vec![]];
let (prio, pred) = dijkstra_heap(&g, 0);
assert_eq!(prio, vec![0, 10, 5]);
assert_eq!(pred, vec![usize::MAX, 0, 1]);
}
File renamed without changes.

0 comments on commit 5d51f25

Please sign in to comment.