use std::cmp::Reverse;
use std::collections::{BTreeMap, BinaryHeap};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Candidate<'a> {
pub id: &'a str,
pub weight: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Term<'a> {
pub count: usize,
pub candidates: &'a [Candidate<'a>],
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Assignment {
pub terms: Vec<Vec<String>>,
}
#[must_use]
pub fn jointly_fillable(terms: &[Term<'_>]) -> bool {
let instance = Instance::new(terms);
let Some(demands) = demands(terms, &instance) else {
return false;
};
let unused = vec![false; instance.hosts.len()];
let mut scratch = FlowScratch::default();
instance
.solve_flow(&instance.eligible, &demands, &unused, &mut scratch)
.is_some()
}
#[must_use]
pub fn assign(terms: &[Term<'_>]) -> Option<Assignment> {
if let [term] = terms {
if term.count == 1 {
let mut best: Option<Candidate<'_>> = None;
for candidate in term.candidates {
best = match best {
Some(held)
if held.weight > candidate.weight
|| (held.weight == candidate.weight && held.id <= candidate.id) =>
{
Some(held)
}
_ => Some(*candidate),
};
}
return best.map(|chosen| Assignment {
terms: vec![vec![chosen.id.to_owned()]],
});
}
}
let instance = Instance::new(terms);
let demands = demands(terms, &instance)?;
let slots = demands.iter().copied().fold(0_usize, usize::saturating_add);
let eligible = instance.pruned(slots);
let mut used = vec![false; instance.hosts.len()];
let mut scratch = FlowScratch::default();
let best = instance.solve_flow(&eligible, &demands, &used, &mut scratch)?;
let mut witness = std::mem::take(&mut scratch.witness);
let mut remaining = demands;
let mut cursors = vec![0_usize; terms.len()];
let mut chosen: Vec<Vec<String>> = vec![Vec::new(); terms.len()];
let mut pinned = 0_i64;
for (term, candidates) in eligible.iter().enumerate() {
for _ in 0..terms[term].count {
loop {
let Some(&host) = candidates.get(cursors[term]) else {
debug_assert!(
false,
"an optimal completion always has a candidate left to pin"
);
return None;
};
cursors[term] += 1;
if used[host] {
continue;
}
if let Some(pos) = witness[term].iter().position(|&assigned| assigned == host) {
witness[term].remove(pos);
used[host] = true;
remaining[term] -= 1;
pinned += instance.weights[host];
chosen[term].push(instance.hosts[host].to_owned());
break;
}
used[host] = true;
remaining[term] -= 1;
let required = best - pinned - instance.weights[host];
if let Some(total) = instance.solve_flow(&eligible, &remaining, &used, &mut scratch)
&& total == required
{
std::mem::swap(&mut witness, &mut scratch.witness);
pinned += instance.weights[host];
chosen[term].push(instance.hosts[host].to_owned());
break;
}
used[host] = false;
remaining[term] += 1;
}
}
}
Some(Assignment { terms: chosen })
}
fn demands(terms: &[Term<'_>], instance: &Instance<'_>) -> Option<Vec<usize>> {
terms
.iter()
.zip(&instance.eligible)
.map(|(term, eligible)| (eligible.len() >= term.count).then_some(term.count))
.collect()
}
struct Instance<'a> {
hosts: Vec<&'a str>,
weights: Vec<i64>,
eligible: Vec<Vec<usize>>,
}
impl<'a> Instance<'a> {
fn new(terms: &[Term<'a>]) -> Self {
let mut weights: BTreeMap<&'a str, i64> = BTreeMap::new();
for term in terms {
for candidate in term.candidates {
let weight = i64::from(candidate.weight);
weights
.entry(candidate.id)
.and_modify(|held| *held = (*held).max(weight))
.or_insert(weight);
}
}
let hosts: Vec<&'a str> = weights.keys().copied().collect();
let weights: Vec<i64> = weights.values().copied().collect();
let eligible = terms
.iter()
.map(|term| {
let mut hosts_of: Vec<usize> = term
.candidates
.iter()
.filter_map(|candidate| hosts.binary_search(&candidate.id).ok())
.collect();
hosts_of.sort_unstable();
hosts_of.dedup();
hosts_of
})
.collect();
Self {
hosts,
weights,
eligible,
}
}
fn pruned(&self, slots: usize) -> Vec<Vec<usize>> {
self.eligible
.iter()
.map(|term| {
let mut ranked = term.clone();
ranked.sort_by(|left, right| {
self.weights[*right]
.cmp(&self.weights[*left])
.then(left.cmp(right))
});
ranked.truncate(slots);
ranked.sort_unstable();
ranked
})
.collect()
}
fn solve_flow(
&self,
eligible: &[Vec<usize>],
demands: &[usize],
used: &[bool],
scratch: &mut FlowScratch,
) -> Option<i64> {
let mut desired = 0_i64;
for &demand in demands {
desired = desired.saturating_add(i64::try_from(demand).unwrap_or(i64::MAX));
}
let term_count = demands.len();
if scratch.witness.len() != term_count {
scratch.witness.resize_with(term_count, Vec::new);
}
for assigned in &mut scratch.witness {
assigned.clear();
}
if desired <= 0 {
return Some(0);
}
scratch.host_slot.clear();
scratch.host_slot.resize(self.hosts.len(), usize::MAX);
scratch.active_hosts.clear();
for (term, hosts) in eligible.iter().enumerate() {
if demands[term] == 0 {
continue;
}
for &host in hosts {
if !used[host] && scratch.host_slot[host] == usize::MAX {
scratch.host_slot[host] = scratch.active_hosts.len();
scratch.active_hosts.push(host);
}
}
}
if i64::try_from(scratch.active_hosts.len()).unwrap_or(i64::MAX) < desired {
return None;
}
let active_count = scratch.active_hosts.len();
let source = 0;
let sink = term_count + active_count + 1;
scratch.flow.reset(sink + 1);
for (term, &demand) in demands.iter().enumerate() {
if demand == 0 {
continue;
}
let capacity = i64::try_from(demand).unwrap_or(i64::MAX);
scratch.flow.add(source, 1 + term, capacity, 0);
}
scratch.potential.clear();
scratch.potential.resize(sink + 1, 0);
let mut sink_dist = FAR;
for (local, &host) in scratch.active_hosts.iter().enumerate() {
let cost = -self.weights[host];
let node = 1 + term_count + local;
scratch.potential[node] = cost;
sink_dist = sink_dist.min(cost);
scratch.flow.add(node, sink, 1, 0);
}
if sink_dist < FAR {
scratch.potential[sink] = sink_dist;
}
for (term, hosts) in eligible.iter().enumerate() {
if demands[term] == 0 {
continue;
}
for &host in hosts {
let local = scratch.host_slot[host];
if local == usize::MAX {
continue;
}
scratch
.flow
.add(1 + term, 1 + term_count + local, 1, -self.weights[host]);
}
}
let cost = {
let FlowScratch {
flow, potential, ..
} = scratch;
flow.min_cost(source, sink, desired, potential)?
};
for (term, &demand) in demands.iter().enumerate() {
if demand == 0 {
continue;
}
let assigned = &mut scratch.witness[term];
for &edge_index in &scratch.flow.adjacency[1 + term] {
let edge = &scratch.flow.edges[edge_index];
if edge_index % 2 == 0
&& edge.capacity == 0
&& edge.to > term_count
&& edge.to < 1 + term_count + active_count
{
assigned.push(scratch.active_hosts[edge.to - (1 + term_count)]);
}
}
debug_assert!(
assigned.is_sorted(),
"a term's witness is ascending by host, which is ascending by ID"
);
}
Some(-cost)
}
}
#[derive(Default)]
struct FlowScratch {
flow: Flow,
host_slot: Vec<usize>,
active_hosts: Vec<usize>,
potential: Vec<i64>,
witness: Vec<Vec<usize>>,
}
const FAR: i64 = i64::MAX / 4;
#[derive(Default)]
struct Flow {
edges: Vec<FlowEdge>,
adjacency: Vec<Vec<usize>>,
nodes: usize,
distances: Vec<i64>,
previous: Vec<Option<usize>>,
queue: BinaryHeap<Reverse<(i64, usize)>>,
}
struct FlowEdge {
to: usize,
capacity: i64,
cost: i64,
}
impl Flow {
fn reset(&mut self, nodes: usize) {
self.nodes = nodes;
self.edges.clear();
if self.adjacency.len() < nodes {
self.adjacency.resize_with(nodes, Vec::new);
}
for outgoing in &mut self.adjacency[..nodes] {
outgoing.clear();
}
}
fn add(&mut self, from: usize, to: usize, capacity: i64, cost: i64) {
let forward = self.edges.len();
self.edges.push(FlowEdge { to, capacity, cost });
self.edges.push(FlowEdge {
to: from,
capacity: 0,
cost: -cost,
});
self.adjacency[from].push(forward);
self.adjacency[to].push(forward + 1);
}
fn min_cost(
&mut self,
source: usize,
sink: usize,
desired: i64,
potential: &mut [i64],
) -> Option<i64> {
if desired <= 0 {
return Some(0);
}
let mut sent = 0_i64;
let mut total = 0_i64;
while sent < desired {
if !self.shortest_paths(source, sink, potential) {
return None;
}
for (node, distance) in self.distances.iter().enumerate() {
if *distance < FAR {
potential[node] += distance;
}
}
let mut pushed = desired - sent;
let mut node = sink;
while let Some(edge) = self.previous[node] {
pushed = pushed.min(self.edges[edge].capacity);
node = self.edges[edge ^ 1].to;
}
let mut node = sink;
while let Some(edge) = self.previous[node] {
total += self.edges[edge].cost * pushed;
self.edges[edge].capacity -= pushed;
self.edges[edge ^ 1].capacity += pushed;
node = self.edges[edge ^ 1].to;
}
sent += pushed;
}
Some(total)
}
fn shortest_paths(&mut self, source: usize, sink: usize, potential: &[i64]) -> bool {
let Self {
edges,
adjacency,
nodes,
distances,
previous,
queue,
} = self;
distances.clear();
distances.resize(*nodes, FAR);
previous.clear();
previous.resize(*nodes, None);
queue.clear();
distances[source] = 0;
queue.push(Reverse((0_i64, source)));
while let Some(Reverse((distance, node))) = queue.pop() {
if distance > distances[node] {
continue;
}
for &edge_index in &adjacency[node] {
let edge = &edges[edge_index];
if edge.capacity == 0 {
continue;
}
let reduced = edge.cost + potential[node] - potential[edge.to];
let candidate = distance + reduced;
if candidate < distances[edge.to] {
distances[edge.to] = candidate;
previous[edge.to] = Some(edge_index);
queue.push(Reverse((candidate, edge.to)));
}
}
}
distances[sink] < FAR
}
}
#[cfg(test)]
mod tests {
use super::{Candidate, Term, assign, jointly_fillable};
fn solve(terms: &[(usize, &[(&str, i32)])]) -> Option<Vec<Vec<String>>> {
let candidates: Vec<Vec<Candidate<'_>>> = terms
.iter()
.map(|(_, hosts)| {
hosts
.iter()
.map(|&(id, weight)| Candidate { id, weight })
.collect()
})
.collect();
let built: Vec<Term<'_>> = terms
.iter()
.zip(&candidates)
.map(|((count, _), candidates)| Term {
count: *count,
candidates,
})
.collect();
assign(&built).map(|assignment| assignment.terms)
}
fn fillable(terms: &[(usize, &[(&str, i32)])]) -> bool {
let candidates: Vec<Vec<Candidate<'_>>> = terms
.iter()
.map(|(_, hosts)| {
hosts
.iter()
.map(|&(id, weight)| Candidate { id, weight })
.collect()
})
.collect();
let built: Vec<Term<'_>> = terms
.iter()
.zip(&candidates)
.map(|((count, _), candidates)| Term {
count: *count,
candidates,
})
.collect();
jointly_fillable(&built)
}
fn ids(ids: &[&str]) -> Vec<String> {
ids.iter().map(|id| (*id).to_owned()).collect()
}
#[test]
fn the_heaviest_assignment_wins_before_ids() {
let first = [("ana", 3), ("bo", 3), ("cy", 1)];
let second = [("ana", 3), ("bo", 3)];
assert_eq!(
solve(&[(1, &first), (1, &second)]),
Some(vec![ids(&["ana"]), ids(&["bo"])])
);
}
#[test]
fn the_tie_break_is_term_ordered_lexicographic_not_a_rank_sum() {
let first = [("a", 0), ("b", 0), ("c", 0)];
let second = [("a", 0), ("b", 0), ("d", 0)];
assert_eq!(
solve(&[(2, &first), (1, &second)]),
Some(vec![ids(&["a", "b"]), ids(&["d"])])
);
}
#[test]
fn each_term_may_have_enough_candidates_yet_the_pools_cannot_fill_jointly() {
let only = [("ana", 1)];
assert!(!fillable(&[(1, &only), (1, &only)]));
assert_eq!(solve(&[(1, &only), (1, &only)]), None);
let shared = [("ana", 1), ("bo", 1)];
assert!(!fillable(&[(2, &shared), (1, &shared)]));
assert_eq!(solve(&[(2, &shared), (1, &shared)]), None);
}
#[test]
fn zero_redundancy_pools_are_still_fillable() {
let ana = [("ana", 1)];
let bo = [("bo", 2)];
assert!(fillable(&[(1, &ana), (1, &bo)]));
assert_eq!(
solve(&[(1, &ana), (1, &bo)]),
Some(vec![ids(&["ana"]), ids(&["bo"])])
);
}
#[test]
fn a_term_with_fewer_candidates_than_it_needs_is_rejected_immediately() {
let pool = [("ana", 1), ("bo", 2)];
assert_eq!(solve(&[(3, &pool)]), None);
assert!(!fillable(&[(3, &pool)]));
assert_eq!(solve(&[(usize::MAX, &pool)]), None);
assert!(!fillable(&[(usize::MAX, &pool)]));
}
#[test]
fn candidates_beyond_the_top_slots_do_not_change_the_winner() {
let first = [("h0", 5), ("h1", 4), ("h2", 3)];
let second = [("h0", 5), ("h1", 4)];
assert_eq!(
solve(&[(1, &first), (1, &second)]),
Some(vec![ids(&["h0"]), ids(&["h1"])])
);
let early_low = [("aaa", 0), ("zzz", 7)];
assert_eq!(solve(&[(1, &early_low)]), Some(vec![ids(&["zzz"])]));
}
#[test]
fn a_witness_replaced_mid_loop_still_ends_at_the_lexicographic_answer() {
let pool = [
("ha", 0),
("hb", 0),
("hc", 0),
("hd", 0),
("he", 0),
("hf", 0),
];
let narrower = [("ha", 0), ("hc", 0), ("hd", 0), ("he", 0), ("hf", 0)];
assert_eq!(
solve(&[(1, &pool), (2, &narrower)]),
Some(vec![ids(&["ha"]), ids(&["hc", "hd"])])
);
}
#[test]
fn one_term_needing_one_host_takes_the_heaviest_then_the_smallest_id() {
let forward = [("ana", 4), ("bo", 4), ("cy", 1)];
let reversed = [("cy", 1), ("bo", 4), ("ana", 4)];
assert_eq!(solve(&[(1, &forward)]), Some(vec![ids(&["ana"])]));
assert_eq!(solve(&[(1, &reversed)]), Some(vec![ids(&["ana"])]));
let empty: [(&str, i32); 0] = [];
assert_eq!(solve(&[(1, &empty)]), None);
}
#[test]
fn extreme_weights_sum_exactly() {
let pool = [("low", i32::MIN), ("high", i32::MAX)];
assert_eq!(solve(&[(2, &pool)]), Some(vec![ids(&["high", "low"])]));
assert_eq!(solve(&[(1, &pool)]), Some(vec![ids(&["high"])]));
}
#[test]
fn terms_needing_no_hosts_are_empty_lists() {
assert_eq!(solve(&[]), Some(Vec::new()));
let pool = [("ana", 1)];
assert_eq!(
solve(&[(0, &pool), (1, &pool)]),
Some(vec![Vec::new(), ids(&["ana"])])
);
assert!(fillable(&[(0, &pool)]));
}
#[test]
fn duplicate_listings_collapse_to_one_candidate() {
let pool = [
Candidate {
id: "ana",
weight: 1,
},
Candidate {
id: "ana",
weight: 5,
},
];
let terms = [Term {
count: 1,
candidates: &pool,
}];
assert_eq!(
assign(&terms),
Some(super::Assignment {
terms: vec![ids(&["ana"])]
})
);
assert!(jointly_fillable(&terms));
let heavy_first = [("ana", 10), ("ana", 5), ("bo", 7)];
let heavy_last = [("ana", 5), ("bo", 7), ("ana", 10)];
assert_eq!(solve(&[(1, &heavy_first)]), Some(vec![ids(&["ana"])]));
assert_eq!(solve(&[(1, &heavy_last)]), Some(vec![ids(&["ana"])]));
let two_slots = [Term {
count: 2,
candidates: &pool,
}];
assert_eq!(assign(&two_slots), None);
assert!(!jointly_fillable(&two_slots));
}
}