use alloc::{collections::VecDeque, vec, vec::Vec};
use core::hash::Hash;
use crate::visit::{
EdgeRef, GraphBase, IntoEdges, IntoNeighbors, IntoNodeIdentifiers, NodeCount, NodeIndexable,
VisitMap, Visitable,
};
pub struct Matching<G: GraphBase> {
graph: G,
mate: Vec<Option<G::NodeId>>,
n_edges: usize,
}
impl<G> Matching<G>
where
G: GraphBase,
{
fn new(graph: G, mate: Vec<Option<G::NodeId>>, n_edges: usize) -> Self {
Self {
graph,
mate,
n_edges,
}
}
}
impl<G> Matching<G>
where
G: NodeIndexable,
{
pub fn mate(&self, node: G::NodeId) -> Option<G::NodeId> {
self.mate.get(self.graph.to_index(node)).and_then(|&id| id)
}
pub fn edges(&self) -> MatchedEdges<'_, G> {
MatchedEdges {
graph: &self.graph,
mate: self.mate.as_slice(),
current: 0,
}
}
pub fn nodes(&self) -> MatchedNodes<'_, G> {
MatchedNodes {
graph: &self.graph,
mate: self.mate.as_slice(),
current: 0,
}
}
pub fn contains_edge(&self, a: G::NodeId, b: G::NodeId) -> bool {
match self.mate(a) {
Some(mate) => mate == b,
None => false,
}
}
pub fn contains_node(&self, node: G::NodeId) -> bool {
self.mate(node).is_some()
}
pub fn len(&self) -> usize {
self.n_edges
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<G> Matching<G>
where
G: NodeCount,
{
pub fn is_perfect(&self) -> bool {
let n_nodes = self.graph.node_count();
n_nodes % 2 == 0 && self.n_edges == n_nodes / 2
}
}
trait WithDummy: NodeIndexable {
fn dummy_idx(&self) -> usize;
fn try_from_index(&self, i: usize) -> Option<Self::NodeId>;
}
impl<G: NodeIndexable> WithDummy for G {
fn dummy_idx(&self) -> usize {
self.node_bound()
}
fn try_from_index(&self, i: usize) -> Option<Self::NodeId> {
if i != self.dummy_idx() {
Some(self.from_index(i))
} else {
None
}
}
}
pub struct MatchedNodes<'a, G: GraphBase> {
graph: &'a G,
mate: &'a [Option<G::NodeId>],
current: usize,
}
impl<G> Iterator for MatchedNodes<'_, G>
where
G: NodeIndexable,
{
type Item = G::NodeId;
fn next(&mut self) -> Option<Self::Item> {
while self.current != self.mate.len() {
let current = self.current;
self.current += 1;
if self.mate[current].is_some() {
return Some(self.graph.from_index(current));
}
}
None
}
}
pub struct MatchedEdges<'a, G: GraphBase> {
graph: &'a G,
mate: &'a [Option<G::NodeId>],
current: usize,
}
impl<G> Iterator for MatchedEdges<'_, G>
where
G: NodeIndexable,
{
type Item = (G::NodeId, G::NodeId);
fn next(&mut self) -> Option<Self::Item> {
while self.current != self.mate.len() {
let current = self.current;
self.current += 1;
if let Some(mate) = self.mate[current] {
if self.graph.to_index(mate) > current {
let this = self.graph.from_index(current);
return Some((this, mate));
}
}
}
None
}
}
pub fn greedy_matching<G>(graph: G) -> Matching<G>
where
G: Visitable + IntoNodeIdentifiers + NodeIndexable + IntoNeighbors,
G::NodeId: Eq + Hash,
G::EdgeId: Eq + Hash,
{
let (mates, n_edges) = greedy_matching_inner(&graph);
Matching::new(graph, mates, n_edges)
}
#[inline]
fn greedy_matching_inner<G>(graph: &G) -> (Vec<Option<G::NodeId>>, usize)
where
G: Visitable + IntoNodeIdentifiers + NodeIndexable + IntoNeighbors,
{
let mut mate = vec![None; graph.node_bound()];
let mut n_edges = 0;
let visited = &mut graph.visit_map();
for start in graph.node_identifiers() {
let mut last = Some(start);
non_backtracking_dfs(graph, start, visited, |next| {
if let Some(pred) = last.take() {
mate[graph.to_index(pred)] = Some(next);
mate[graph.to_index(next)] = Some(pred);
n_edges += 1;
} else {
last = Some(next);
}
});
}
(mate, n_edges)
}
fn non_backtracking_dfs<G, F>(graph: &G, source: G::NodeId, visited: &mut G::Map, mut visitor: F)
where
G: Visitable + IntoNeighbors,
F: FnMut(G::NodeId),
{
if visited.visit(source) {
for target in graph.neighbors(source) {
if !visited.is_visited(&target) {
visitor(target);
non_backtracking_dfs(graph, target, visited, visitor);
break;
}
}
}
}
#[derive(Clone, Copy, Default)]
enum Label<G: GraphBase> {
#[default]
None,
Start,
Vertex(G::NodeId),
Edge(G::EdgeId, [G::NodeId; 2]),
Flag(G::EdgeId),
}
impl<G: GraphBase> Label<G> {
fn is_outer(&self) -> bool {
self != &Label::None && !matches!(self, Label::Flag(_))
}
fn is_inner(&self) -> bool {
!self.is_outer()
}
fn to_vertex(&self) -> Option<G::NodeId> {
match *self {
Label::Vertex(v) => Some(v),
_ => None,
}
}
fn is_flagged(&self, edge: G::EdgeId) -> bool {
matches!(self, Label::Flag(flag) if flag == &edge)
}
}
impl<G: GraphBase> PartialEq for Label<G> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Label::None, Label::None) => true,
(Label::Start, Label::Start) => true,
(Label::Vertex(v1), Label::Vertex(v2)) => v1 == v2,
(Label::Edge(e1, _), Label::Edge(e2, _)) => e1 == e2,
(Label::Flag(e1), Label::Flag(e2)) => e1 == e2,
_ => false,
}
}
}
pub fn maximum_matching<G>(graph: G) -> Matching<G>
where
G: Visitable + NodeIndexable + IntoNodeIdentifiers + IntoEdges,
{
assert_ne!(
graph.node_bound(),
usize::MAX,
"The input graph capacity should be strictly less than core::usize::MAX."
);
let (mut mate, mut n_edges) = greedy_matching_inner(&graph);
mate.push(None);
let len = graph.node_bound() + 1;
debug_assert_eq!(mate.len(), len);
let mut label: Vec<Label<G>> = vec![Label::None; len];
let mut first_inner = vec![usize::MAX; len];
let visited = &mut graph.visit_map();
let mut queue = VecDeque::new();
for start in 0..graph.node_bound() {
if mate[start].is_some() {
continue;
}
label[start] = Label::Start;
first_inner[start] = graph.dummy_idx();
graph.reset_map(visited);
let start = graph.from_index(start);
queue.push_back(start);
visited.visit(start);
'search: while let Some(outer_vertex) = queue.pop_front() {
for edge in graph.edges(outer_vertex) {
if edge.source() == edge.target() {
continue;
}
let other_vertex = edge.target();
let other_idx = graph.to_index(other_vertex);
if mate[other_idx].is_none() && other_vertex != start {
mate[other_idx] = Some(outer_vertex);
augment_path(&graph, outer_vertex, other_vertex, &mut mate, &label);
n_edges += 1;
break 'search;
} else if label[other_idx].is_outer() {
find_join(
&graph,
edge,
&mate,
&mut label,
&mut first_inner,
|labeled| {
if visited.visit(labeled) {
queue.push_back(labeled);
}
},
);
} else {
let mate_vertex = mate[other_idx];
let mate_idx = mate_vertex.map_or(graph.dummy_idx(), |id| graph.to_index(id));
if label[mate_idx].is_inner() {
label[mate_idx] = Label::Vertex(outer_vertex);
first_inner[mate_idx] = other_idx;
}
if let Some(mate_vertex) = mate_vertex {
if visited.visit(mate_vertex) {
queue.push_back(mate_vertex);
}
}
}
}
}
for lbl in label.iter_mut() {
*lbl = Label::None;
}
queue.clear();
}
mate.pop();
Matching::new(graph, mate, n_edges)
}
fn find_join<G, F>(
graph: &G,
edge: G::EdgeRef,
mate: &[Option<G::NodeId>],
label: &mut [Label<G>],
first_inner: &mut [usize],
mut visitor: F,
) where
G: IntoEdges + NodeIndexable + Visitable,
F: FnMut(G::NodeId),
{
let source = graph.to_index(edge.source());
let target = graph.to_index(edge.target());
let mut left = first_inner[source];
let mut right = first_inner[target];
if left == right {
return;
}
let flag = Label::Flag(edge.id());
label[left] = flag;
label[right] = flag;
let join = loop {
if right != graph.dummy_idx() {
core::mem::swap(&mut left, &mut right);
}
let left_mate = graph.to_index(mate[left].unwrap());
let next_inner = label[left_mate].to_vertex().unwrap();
left = first_inner[graph.to_index(next_inner)];
if !label[left].is_flagged(edge.id()) {
label[left] = flag;
} else {
break left;
}
};
for endpoint in [source, target].iter().copied() {
let mut inner = first_inner[endpoint];
while inner != join {
if let Some(ix) = graph.try_from_index(inner) {
visitor(ix);
}
label[inner] = Label::Edge(edge.id(), [edge.source(), edge.target()]);
first_inner[inner] = join;
let inner_mate = graph.to_index(mate[inner].unwrap());
let next_inner = label[inner_mate].to_vertex().unwrap();
inner = first_inner[graph.to_index(next_inner)];
}
}
for (vertex_idx, vertex_label) in label.iter().enumerate() {
if vertex_idx != graph.dummy_idx()
&& vertex_label.is_outer()
&& label[first_inner[vertex_idx]].is_outer()
{
first_inner[vertex_idx] = join;
}
}
}
fn augment_path<G>(
graph: &G,
outer: G::NodeId,
other: G::NodeId,
mate: &mut [Option<G::NodeId>],
label: &[Label<G>],
) where
G: NodeIndexable,
{
let outer_idx = graph.to_index(outer);
let temp = mate[outer_idx];
let temp_idx = temp.map_or(graph.dummy_idx(), |id| graph.to_index(id));
mate[outer_idx] = Some(other);
if mate[temp_idx] != Some(outer) {
} else if let Label::Vertex(vertex) = label[outer_idx] {
mate[temp_idx] = Some(vertex);
if let Some(temp) = temp {
augment_path(graph, vertex, temp, mate, label);
}
} else if let Label::Edge(_, [source, target]) = label[outer_idx] {
augment_path(graph, source, target, mate, label);
augment_path(graph, target, source, mate, label);
} else {
panic!("Unexpected label when augmenting path");
}
}