aoc/year2017/day07.rs
1//! # Recursive Circus
2//!
3//! Tree structures are tricky to implement in Rust, requiring wrapping the pointer in a [`Rc`].
4//! To avoid this we store the tree "upside down" with each node containing a single index to its
5//! parent, stored in a flat `vec`.
6//!
7//! We rely on a special structure of the input that the unbalanced node requiring change will
8//! always be the lowest node in the tree and have at least two other balanced siblings
9//! so that we can disambiguate.
10//!
11//! [`Rc`]: std::rc::Rc
12use crate::util::hash::*;
13use crate::util::parse::*;
14
15type Input = (String, i32);
16
17#[derive(Clone, Copy, Default)]
18struct Node {
19 parent: Option<usize>,
20 children: usize,
21 processed: usize,
22 weight: i32,
23 total: i32,
24 sub_weights: [i32; 2],
25 sub_totals: [i32; 2],
26}
27
28pub fn parse(input: &str) -> Input {
29 // Split each line into the program name then the rest of the information.
30 let pairs: Vec<_> = input.lines().map(|line| line.split_once(' ').unwrap()).collect();
31 // Convert each program name into a fixed index so that we can use faster vec lookups
32 // later on when processing the tree.
33 let indices: FastMap<_, _> = pairs.iter().enumerate().map(|(i, &(key, _))| (key, i)).collect();
34 // Create a vec of the correct size with default values.
35 let mut nodes = vec![Node::default(); indices.len()];
36
37 for (i, &(_, suffix)) in pairs.iter().enumerate() {
38 // Remove delimiters.
39 let mut iter = suffix.split(|c: char| !c.is_ascii_alphanumeric()).filter(|s| !s.is_empty());
40
41 let weight = iter.next().unwrap().signed();
42 nodes[i].weight = weight;
43 nodes[i].total = weight;
44
45 for edge in iter {
46 nodes[i].children += 1;
47 let child = indices[edge];
48 nodes[child].parent = Some(i);
49 }
50 }
51
52 // The root is the only node without a parent. Start from any node, and walk up the
53 // tree until finding the root.
54 let mut candidate = 0;
55 while let Some(parent) = nodes[candidate].parent {
56 candidate = parent;
57 }
58 let part_one = pairs[candidate].0.to_owned();
59 let mut part_two = 0;
60
61 // Process nodes from leaf to root, starting with leaf nodes.
62 let mut todo: Vec<_> = (0..nodes.len()).filter(|&i| nodes[i].children == 0).collect();
63
64 while let Some(index) = todo.pop() {
65 let Node { parent, weight, total, .. } = nodes[index];
66 let parent = parent.unwrap();
67 let node = &mut nodes[parent];
68
69 if node.processed < 2 {
70 // Fill out the first two children in any order.
71 node.sub_weights[node.processed] = weight;
72 node.sub_totals[node.processed] = total;
73 } else {
74 // Representing the balanced nodes as `b` and the unbalanced node as `u`,
75 // there are 4 possibilities:
76 // b3 + [b1 b2] => [b2 b1] Swap, keep accumulating
77 // b3 + [b1 u2] => [u2 b1] Swap, unbalanced node identified
78 // u3 + [b1 b2] -> [u3 b2] Overwrite, unbalanced node identified
79 // b3 + [u1 b2] => [u1 b2] Do nothing, unbalanced node identified
80 // The unbalanced node will always be first (if it exists).
81 if node.sub_totals[0] == total {
82 node.sub_weights.swap(0, 1);
83 node.sub_totals.swap(0, 1);
84 } else if node.sub_totals[1] != total {
85 node.sub_weights[0] = weight;
86 node.sub_totals[0] = total;
87 }
88
89 // If the unbalanced node was identified, it is now first, and we can short-circuit
90 // summing the weights of the rest of the tree.
91 let [x, y] = node.sub_totals;
92
93 if x != y {
94 part_two = node.sub_weights[0] - x + y;
95 break;
96 }
97 }
98
99 // Total is a node's weight plus the sum of all children recursively.
100 node.total += total;
101 node.processed += 1;
102
103 // If we've processed all children then add to the stack and check balance.
104 if node.processed == node.children {
105 todo.push(parent);
106 }
107 }
108
109 (part_one, part_two)
110}
111
112pub fn part1(input: &Input) -> &str {
113 &input.0
114}
115
116pub fn part2(input: &Input) -> i32 {
117 input.1
118}