
    hT                        S r SSKrSSKrSSKrSSKJr  SSKJ	r	  / SQr
\" S5      r\R                  SS j5       r\R                  SS j5       rS	 rS
 r\R                  SS j5       r\r\R                  " SS9SS j5       rg)a'  Provides functions for computing maximum cardinality matchings and minimum
weight full matchings in a bipartite graph.

If you don't care about the particular implementation of the maximum matching
algorithm, simply use the :func:`maximum_matching`. If you do care, you can
import one of the named maximum matching algorithms directly.

For example, to find a maximum matching in the complete bipartite graph with
two vertices on the left and three vertices on the right:

>>> G = nx.complete_bipartite_graph(2, 3)
>>> left, right = nx.bipartite.sets(G)
>>> list(left)
[0, 1]
>>> list(right)
[2, 3, 4]
>>> nx.bipartite.maximum_matching(G)
{0: 2, 1: 3, 2: 0, 3: 1}

The dictionary returned by :func:`maximum_matching` includes a mapping for
vertices in both the left and right vertex sets.

Similarly, :func:`minimum_weight_full_matching` produces, for a complete
weighted bipartite graph, a matching whose cardinality is the cardinality of
the smaller of the two partitions, and for which the sum of the weights of the
edges included in the matching is minimal.

    N)sets)biadjacency_matrix)maximum_matchinghopcroft_karp_matchingeppstein_matchingto_vertex_coverminimum_weight_full_matchinginfc                   ^ ^^^	^
^^ U UU	U
UU4S jnU UUU
U4S jm[        T U5      u  m	nT	 Vs0 s H  oDS_M     snm
U Vs0 s H  oDS_M     snm0 m[        R                  " 5       mSnU" 5       (       a3  T	 H  nT
U   b  M  T" U5      (       d  M  US-  nM!     U" 5       (       a  M3  T
R                  5        VVs0 s H  u  pdUc  M
  Xd_M     snnm
TR                  5        VVs0 s H  u  pdUc  M
  Xd_M     snnm[	        [
        R                  " T
R                  5       TR                  5       5      5      $ s  snf s  snf s  snnf s  snnf )a  Returns the maximum cardinality matching of the bipartite graph `G`.

A matching is a set of edges that do not share any nodes. A maximum
cardinality matching is a matching with the most edges possible. It
is not always unique. Finding a matching in a bipartite graph can be
treated as a networkx flow problem.

The functions ``hopcroft_karp_matching`` and ``maximum_matching``
are aliases of the same function.

Parameters
----------
G : NetworkX graph

  Undirected bipartite graph

top_nodes : container of nodes

  Container with all nodes in one bipartite node set. If not supplied
  it will be computed. But if more than one solution exists an exception
  will be raised.

Returns
-------
matches : dictionary

  The matching is returned as a dictionary, `matches`, such that
  ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
  nodes do not occur as a key in `matches`.

Raises
------
AmbiguousSolution
  Raised if the input bipartite graph is disconnected and no container
  with all nodes in one bipartite set is provided. When determining
  the nodes in each bipartite set more than one valid solution is
  possible if the input graph is disconnected.

Notes
-----
This function is implemented with the `Hopcroft--Karp matching algorithm
<https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm>`_ for
bipartite graphs.

See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
for further details on how bipartite graphs are handled in NetworkX.

See Also
--------
maximum_matching
hopcroft_karp_matching
eppstein_matching

References
----------
.. [1] John E. Hopcroft and Richard M. Karp. "An n^{5 / 2} Algorithm for
   Maximum Matchings in Bipartite Graphs" In: **SIAM Journal of Computing**
   2.4 (1973), pp. 225--231. <https://doi.org/10.1137/0202019>.

c                  b  > T H*  n TU    c  STU '   TR                  U 5        M!  [        TU '   M,     [        TS '   T(       ad  TR                  5       n TU    TS    :  a?  TU     H6  nTTU      [        L d  M  TU    S-   TTU   '   TR                  TU   5        M8     T(       a  Md  TS    [        L$ )Nr      )appendINFINITYpopleft)vuG	distancesleftleftmatchesqueuerightmatchess     X/var/www/html/env/lib/python3.13/site-packages/networkx/algorithms/bipartite/matching.pybreadth_first_search4hopcroft_karp_matching.<locals>.breadth_first_search   s    A1~% 	!Q'	!  #	$A|io-1A a1X=5>q\A5E	,q/2\!_5  e h..    c                    > U bF  TU     H3  nTTU      TU    S-   :X  d  M  T" TU   5      (       d  M)  U TU'   UTU '     g   [         TU '   gg)Nr   TF)r   )r   r   r   depth_first_searchr   r   r   s     r   r   2hopcroft_karp_matching.<locals>.depth_first_search   se    =qT\!_-11AA),q/::*+Q)*A#  $IaLr   Nr   r   )bipartite_setscollectionsdequeitemsdict	itertoolschain)r   	top_nodesr   rightr   num_matched_pairskr   r   r   r   r   r   s   `      @@@@@@r   r   r   :   s:   J/ /"
 
 !I.KD%$()Dqd7D)K%*+UtGU+LIE 

 
 A1~%%a((%*%  
 
  %0$5$5$7I$7DA1414$7IK%1%7%7%9K%9TQQDAD%9KL 	 1 1 3\5G5G5IJKK1 *+ JKs#   D:D?=	E
E'	E
4E
c                   ^	^
^^^ [        X5      u  p#[        R                  " U R                  U5      5      n 0 m	U  H  nX    H  nUT	;  d  M  UT	U'     M     M      0 m/ mU  Vs0 s H  oDT_M     snm
T	 H	  nT
T	U   	 M     [	        T
5      nU(       a  T(       d  0 nU H7  nX    H,  nUT;  d  M  UR                  U/ 5      R                  U5        M.     M9     / nU H?  nXu   TU'   UT	;   a  UR                  T	U   5        UT
T	U   '   M.  TR                  U5        MA     U(       a	  T(       d  M  T(       d!  T	R                  5        H  nUT	T	U   '   M     T	$ U	U
UUU4S jmT H  nT" U5        M     GM  s  snf )a  Returns the maximum cardinality matching of the bipartite graph `G`.

Parameters
----------
G : NetworkX graph

  Undirected bipartite graph

top_nodes : container

  Container with all nodes in one bipartite node set. If not supplied
  it will be computed. But if more than one solution exists an exception
  will be raised.

Returns
-------
matches : dictionary

  The matching is returned as a dictionary, `matching`, such that
  ``matching[v] == w`` if node `v` is matched to node `w`. Unmatched
  nodes do not occur as a key in `matching`.

Raises
------
AmbiguousSolution
  Raised if the input bipartite graph is disconnected and no container
  with all nodes in one bipartite set is provided. When determining
  the nodes in each bipartite set more than one valid solution is
  possible if the input graph is disconnected.

Notes
-----
This function is implemented with David Eppstein's version of the algorithm
Hopcroft--Karp algorithm (see :func:`hopcroft_karp_matching`), which
originally appeared in the `Python Algorithms and Data Structures library
(PADS) <http://www.ics.uci.edu/~eppstein/PADS/ABOUT-PADS.txt>`_.

See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
for further details on how bipartite graphs are handled in NetworkX.

See Also
--------

hopcroft_karp_matching

c                    > U T;   aL  TR                  U 5      nU H5  nUT;   d  M  TR                  U5      nUTL d  T" U5      (       d  M0  UTU '     g   g)NTF)pop)	r   Lr   pumatchingpredpredsrecurse	unmatcheds	       r   r3   "eppstein_matching.<locals>.recurse5  sU    EzIIaLADy!XXa[?gbkk*+HQK#'  r   )r    nxDiGraphedgeslist
setdefaultr   copy)r   r'   r   r(   r   r   layernewLayerkeyr0   r1   r2   r3   r4   s            @@@@@r   r   r      s   d !.KD


1774=!AHA   
  	&'(a9a(AXa[! T
 IHA~ ++Ar299!<   E#;a=LL!-()D!%$$Q'  II  8  }}*-#' 'O		 		 AAJ Y  )s   %E8c                 J   ^ ^^^ SU UUU4S jjnU" USS9=(       d    U" USS9$ )a  Returns True if and only if the vertex `v` is connected to one of
the target vertices by an alternating path in `G`.

An *alternating path* is a path in which every other edge is in the
specified maximum matching (and the remaining edges in the path are not in
the matching). An alternating path may have matched edges in the even
positions or in the odd positions, as long as the edges alternate between
'matched' and 'unmatched'.

`G` is an undirected bipartite NetworkX graph.

`v` is a vertex in `G`.

`matched_edges` is a set of edges present in a maximum matching in `G`.

`unmatched_edges` is a set of edges not present in a maximum
matching in `G`.

`targets` is a set of vertices.

Tc                   > [        5       nU(       a  SOSnU [        T
U    5      U4/nU(       ay  US   u  pVnUS-  (       a  TOTn [        U5      n	X;  aI  XY4U;   d  X4U;   a;  U	T;   a  gUR                  U	5        UR	                  U	[        T
U	   5      US-   45        U(       a  My  g! [
         a    UR                  5          N&f = f)aD  Returns True if and only if `u` is connected to one of the
targets by an alternating path.

`u` is a vertex in the graph `G`.

If `along_matched` is True, this step of the depth-first search
will continue only through edges in the given matching. Otherwise, it
will continue only through edges *not* in the given matching.

r   r      TF)setiternextaddr   StopIterationr-   )r   along_matchedvisitedinitial_depthstackparentchildrendepthvalid_edgeschildr   matched_edgestargetsunmatched_edgess             r   _alternating_dfs;_is_connected_by_alternating_path.<locals>._alternating_dfs[  s     % +T!A$Z/0&+Bi#Fe+019-/K	X'+5%K9W G+#'E*eT!E(^UQY%GH e  ! 		s   $B* ,4B* *CC)rH   F)T )r   r   rQ   rS   rR   rT   s   ` ``` r   !_is_connected_by_alternating_pathrW   D  s1    . D AT2 6F	7 r   c           
         UR                  5        VVs1 s H  u  p4[        X445      iM     nnnU Vs1 s H  n[        U5      iM     nnU R                  5        VVs1 s H  u  p4[        X445      U;  d  M  X44iM     nnnU  Vs1 s H  nXB;   d  [	        XXxU5      (       d  M  UiM      sn$ s  snnf s  snf s  snnf s  snf )a  Returns the set of vertices that are connected to one of the target
vertices by an alternating path in `G` or are themselves a target.

An *alternating path* is a path in which every other edge is in the
specified maximum matching (and the remaining edges in the path are not in
the matching). An alternating path may have matched edges in the even
positions or in the odd positions, as long as the edges alternate between
'matched' and 'unmatched'.

`G` is an undirected bipartite NetworkX graph.

`matching` is a dictionary representing a maximum matching in `G`, as
returned by, for example, :func:`maximum_matching`.

`targets` is a set of vertices.

)r#   	frozensettupler8   rW   )	r   r0   rR   r   r   	edge_setsedgerQ   rS   s	            r   _connected_by_alternating_pathsr]     s    , 08~~/?@/?tqA6"/?I@-67YTU4[YM7WWY&6A)QF*;9*LY   A<,-'
 	
  A7s"   B-B3B87B8B>$B>c                 |    [        X5      u  p4[        U 5      [        U5      -
  nXS-  n[        XU5      nX7-
  XG-  -  $ )a  Returns the minimum vertex cover corresponding to the given maximum
matching of the bipartite graph `G`.

Parameters
----------
G : NetworkX graph

  Undirected bipartite graph

matching : dictionary

  A dictionary whose keys are vertices in `G` and whose values are the
  distinct neighbors comprising the maximum matching for `G`, as returned
  by, for example, :func:`maximum_matching`. The dictionary *must*
  represent the maximum matching.

top_nodes : container

  Container with all nodes in one bipartite node set. If not supplied
  it will be computed. But if more than one solution exists an exception
  will be raised.

Returns
-------
vertex_cover : :class:`set`

  The minimum vertex cover in `G`.

Raises
------
AmbiguousSolution
  Raised if the input bipartite graph is disconnected and no container
  with all nodes in one bipartite set is provided. When determining
  the nodes in each bipartite set more than one valid solution is
  possible if the input graph is disconnected.

Notes
-----
This function is implemented using the procedure guaranteed by `Konig's
theorem
<https://en.wikipedia.org/wiki/K%C3%B6nig%27s_theorem_%28graph_theory%29>`_,
which proves an equivalence between a maximum matching and a minimum vertex
cover in bipartite graphs.

Since a minimum vertex cover is the complement of a maximum independent set
for any graph, one can compute the maximum independent set of a bipartite
graph this way:

>>> G = nx.complete_bipartite_graph(2, 3)
>>> matching = nx.bipartite.maximum_matching(G)
>>> vertex_cover = nx.bipartite.to_vertex_cover(G, matching)
>>> independent_set = set(G) - vertex_cover
>>> print(list(independent_set))
[2, 3, 4]

See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
for further details on how bipartite graphs are handled in NetworkX.

)r    rC   r]   )r   r0   r'   r.   Runmatched_verticesUZs           r   r   r     sK    ~ !'DAQ#h-/A 	(Q7A Eaer   weight)
edge_attrsc                 &   SSK nSSKn[        R                  R	                  X5      u  pV[        U5      n[        U5      n[        XXSS9n	UR                  U	R                  UR                  5      n
U	R                  XR                  U	R                  4'   UR                  R                  U
5      n[        U6  VVs0 s H  u  pX|   X   _M     nnnUR!                  UR#                  5        VVs0 s H  u  pX_M	     snn5        U$ s  snnf s  snnf )u  Returns a minimum weight full matching of the bipartite graph `G`.

Let :math:`G = ((U, V), E)` be a weighted bipartite graph with real weights
:math:`w : E \to \mathbb{R}`. This function then produces a matching
:math:`M \subseteq E` with cardinality

.. math::
   \lvert M \rvert = \min(\lvert U \rvert, \lvert V \rvert),

which minimizes the sum of the weights of the edges included in the
matching, :math:`\sum_{e \in M} w(e)`, or raises an error if no such
matching exists.

When :math:`\lvert U \rvert = \lvert V \rvert`, this is commonly
referred to as a perfect matching; here, since we allow
:math:`\lvert U \rvert` and :math:`\lvert V \rvert` to differ, we
follow Karp [1]_ and refer to the matching as *full*.

Parameters
----------
G : NetworkX graph

  Undirected bipartite graph

top_nodes : container

  Container with all nodes in one bipartite node set. If not supplied
  it will be computed.

weight : string, optional (default='weight')

   The edge data key used to provide each value in the matrix.
   If None, then each edge has weight 1.

Returns
-------
matches : dictionary

  The matching is returned as a dictionary, `matches`, such that
  ``matches[v] == w`` if node `v` is matched to node `w`. Unmatched
  nodes do not occur as a key in `matches`.

Raises
------
ValueError
  Raised if no full matching exists.

ImportError
  Raised if SciPy is not available.

Notes
-----
The problem of determining a minimum weight full matching is also known as
the rectangular linear assignment problem. This implementation defers the
calculation of the assignment to SciPy.

References
----------
.. [1] Richard Manning Karp:
   An algorithm to Solve the m x n Assignment Problem in Expected Time
   O(mn log n).
   Networks, 10(2):143–152, 1980.

r   Ncoo)	row_ordercolumn_orderrc   format)numpyscipyr6   	bipartiter   r9   r   fullshaper
   datarowcoloptimizelinear_sum_assignmentzipupdater#   )r   r'   rc   npspr   r(   ra   Vweights_sparseweightsleft_matchesr   r   ds                  r   r	   r	     s    D ,,##A1KDT
AUA (	QeN ggn**BFF3G6D6I6IG 2 223;;44W=L #\ 23 2qt 2A3 HHqwwy)ytqady)*H	 	4 *s   ;D/D
)N)Nrc   )__doc__r!   r%   networkxr6   networkx.algorithms.bipartiter   r    $networkx.algorithms.bipartite.matrixr   __all__floatr   _dispatchabler   r   rW   r]   r   r   r	   rV   r   r   <module>r      s   :    @ C < {L {L| G GT;|#L G GZ *  X&T 'Tr   