-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.rs
95 lines (83 loc) · 2.37 KB
/
23.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![feature(test)]
#![expect(unstable_name_collisions)]
use aoc::bitset::BitSet;
use itertools::Itertools;
use rustc_hash::FxHashMap;
#[derive(Debug)]
struct Input {
graph: Vec<BitSet>,
names: Vec<String>,
}
fn setup(input: &str) -> Input {
let input = input.lines().map(|l| l.split('-').collect_tuple().unwrap());
let mut idx = FxHashMap::default();
for name in input.clone().flat_map(|(a, b)| [a, b]) {
let i = idx.len();
idx.entry(name).or_insert(i);
}
let mut graph = vec![BitSet::new(); idx.len()];
for (a, b) in input.map(|(a, b)| (idx[a], idx[b])) {
graph[a].insert(b);
graph[b].insert(a);
}
let mut names = vec![String::new(); idx.len()];
for (name, i) in idx {
names[i] = name.into();
}
Input { graph, names }
}
fn max_bron_kerbosch(r: BitSet, mut p: BitSet, mut x: BitSet, graph: &[BitSet]) -> Option<BitSet> {
if p.is_empty() && x.is_empty() {
return Some(r);
}
let mut out = None::<BitSet>;
let u = p.iter().chain(&x).next().unwrap();
for v in &(p.clone() - &graph[u]) {
let mut r = r.clone();
r.insert(v);
let n = &graph[v];
let result = max_bron_kerbosch(r, p.clone() & n, x.clone() & n, graph);
if result.as_ref().map(|s| s.len()) > out.as_ref().map(|s| s.len()) {
out = result;
}
p.remove(v);
x.insert(v);
}
out
}
fn part1(input: &Input) -> usize {
let t = &input
.names
.iter()
.enumerate()
.filter_map(|(i, name)| name.starts_with('t').then_some(i))
.collect::<BitSet>();
input
.graph
.iter()
.enumerate()
.flat_map(|(a, an)| {
an.iter().take_while(move |&b| b < a).flat_map(move |b| {
an.iter()
.take_while(move |&c| c < b)
.filter(move |&c| input.graph[b].contains(c))
.filter(move |&c| [a, b, c].into_iter().any(|i| t.contains(i)))
})
})
.count()
}
fn part2(input: &Input) -> String {
max_bron_kerbosch(
Default::default(),
(0..input.graph.len()).collect(),
Default::default(),
&input.graph,
)
.unwrap()
.into_iter()
.map(|i| input.names[i].as_str())
.sorted_unstable()
.intersperse(",")
.collect()
}
aoc::main!(2024, 23, ex: 1);