|
| 1 | +//! [Day 25: Snowverload](https://adventofcode.com/2023/day/25) |
| 2 | +
|
| 3 | +use rustworkx_core::connectivity::stoer_wagner_min_cut; |
| 4 | +use rustworkx_core::petgraph::graph::Graph; |
| 5 | +use rustworkx_core::petgraph::Undirected; |
| 6 | +use std::collections::HashMap; |
| 7 | + |
| 8 | +type G = Graph<(), (), Undirected>; |
| 9 | + |
| 10 | +struct Puzzle { |
| 11 | + graph: G, |
| 12 | +} |
| 13 | + |
| 14 | +impl Puzzle { |
| 15 | + fn new() -> Self { |
| 16 | + Self { |
| 17 | + graph: G::new_undirected(), |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + /// Get the puzzle input. |
| 22 | + fn configure(&mut self, path: &str) { |
| 23 | + let data = std::fs::read_to_string(path).unwrap(); |
| 24 | + |
| 25 | + let mut nodes = HashMap::new(); |
| 26 | + |
| 27 | + for line in data.lines() { |
| 28 | + let (node, cnx) = line.split_once(": ").unwrap(); |
| 29 | + let connections = cnx.split_ascii_whitespace().collect::<Vec<_>>(); |
| 30 | + |
| 31 | + let node_index = *nodes.entry(node).or_insert_with(|| self.graph.add_node(())); |
| 32 | + |
| 33 | + for connection in connections { |
| 34 | + let connection_index = *nodes |
| 35 | + .entry(connection) |
| 36 | + .or_insert_with(|| self.graph.add_node(())); |
| 37 | + |
| 38 | + self.graph.add_edge(node_index, connection_index, ()); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /// Solve part one. |
| 44 | + fn part1(&mut self) -> usize { |
| 45 | + let min_cut = stoer_wagner_min_cut(&self.graph, |_| Ok::<u32, ()>(1)); |
| 46 | + |
| 47 | + let (_, edges) = min_cut.unwrap().unwrap(); |
| 48 | + |
| 49 | + (self.graph.node_count() - edges.len()) * edges.len() |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +fn main() { |
| 54 | + let args = aoc::parse_args(); |
| 55 | + let mut puzzle = Puzzle::new(); |
| 56 | + puzzle.configure(args.path.as_str()); |
| 57 | + println!("{}", puzzle.part1()); |
| 58 | +} |
| 59 | + |
| 60 | +/// Test from puzzle input |
| 61 | +#[cfg(test)] |
| 62 | +mod test { |
| 63 | + use super::*; |
| 64 | + |
| 65 | + #[test] |
| 66 | + fn test01() { |
| 67 | + let mut puzzle = Puzzle::new(); |
| 68 | + puzzle.configure("test.txt"); |
| 69 | + assert_eq!(puzzle.part1(), 54); |
| 70 | + } |
| 71 | +} |
0 commit comments