Skip to content

Commit

Permalink
sparse representation for flow is much better
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 26, 2023
1 parent de68cfe commit 37e2f63
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 7 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www.
| [Day 22](./src/bin/22.rs) | `78.3µs` | `194.8µs` |
| [Day 23](./src/bin/23.rs) | `330.4µs` | `13.3ms` |
| [Day 24](./src/bin/24.rs) | `257.2µs` | `16.2µs` |
| [Day 25](./src/bin/25.rs) | `722.6µs` | `-` |
| [Day 25](./src/bin/25.rs) | `443.9µs` | `-` |

**Total: 31.24ms**
**Total: 30.96ms**
<!--- benchmarking table --->

---
Expand Down
9 changes: 4 additions & 5 deletions src/bin/25.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn part_one(input: &str) -> Option<usize> {
}

fn find_cut_of_size(net: &mut NetworkFlow, s: usize, t: usize, cut: i16) -> Option<usize> {
net.flow.fill(0);
net.flow.clear();

let mut flow = 0;
while flow <= cut {
Expand Down Expand Up @@ -116,26 +116,25 @@ impl<'a> GraphBuilder<'a> {
struct NetworkFlow {
vertices: usize,
adjacency: Vec<FxHashSet<usize>>,
flow: Vec<i16>,
flow: FxHashMap<(usize, usize), i16>,
pred: Vec<Option<usize>>,
queue: VecDeque<usize>,
}

impl NetworkFlow {
fn flow(&self, a: usize, b: usize) -> i16 {
self.flow[a * self.vertices + b]
self.flow.get(&(a, b)).copied().unwrap_or_default()
}

fn add_flow(&mut self, a: usize, b: usize, df: i16) {
self.flow[a * self.vertices + b] += df;
*self.flow.entry((a, b)).or_default() += df;
}
}

impl From<Graph> for NetworkFlow {
fn from(graph: Graph) -> Self {
let mut ret = Self {
vertices: graph.vertices,
flow: vec![0; graph.vertices * graph.vertices],
pred: vec![None; graph.vertices],
..Default::default()
};
Expand Down

0 comments on commit 37e2f63

Please sign in to comment.