
    `+*                       d Z ddlmZ ddlZddlZddlmZmZmZ ddl	m
Z
mZmZ ddlmZ ddlmZmZmZmZmZmZmZmZ ddlmZ 	 dd	lmZmZ dd
lm Z  ddlm!Z! e!dk  rddl	m"Z# ddl	m$Z% 	 ddl&m'Z' nddlm)Z) 	 ddl*m'Z' ddZ, G d de      Z-d Z. G d de-      Z/e/Z0y# e$ r dd	lmZmZ Y aw xY w# e$ r	 ddl(m'Z' Y @w xY w# e$ r	 ddl+m'Z' Y Qw xY w)ab  Sorted List
==============

:doc:`Sorted Containers<index>` is an Apache2 licensed Python sorted
collections library, written in pure-Python, and fast as C-extensions. The
:doc:`introduction<introduction>` is the best way to get started.

Sorted list implementations:

.. currentmodule:: sortedcontainers

* :class:`SortedList`
* :class:`SortedKeyList`

    )print_functionN)bisect_leftbisect_rightinsort)chainrepeatstarmap)log)addeqnegtgeltleiadd)dedent)SequenceMutableSequence)wraps)
hexversioni   )imap)izip)	get_ident)reducec                       fd}|S )zHDecorator to make a repr function return fillvalue for a recursive call.c                 J     t               t                fd       }|S )Nc                     t        |       t               f}|v rS j                  |       	  |       }j                  |       |S # j                  |       w xY wN)idr   r   discard)selfkeyresult	fillvaluerepr_runninguser_functions      =/usr/lib/python3/dist-packages/sortedcontainers/sortedlist.pywrapperz<recursive_repr.<locals>.decorating_function.<locals>.wrapper@   sc    T(IK'Cl"  S!*&t,$$S)M $$S)s   A
 
A)setr   )r'   r)   r&   r%   s   ` @r(   decorating_functionz+recursive_repr.<locals>.decorating_function=   s(    u	}			 
		      )r%   r+   s   ` r(   recursive_reprr.   7   s    " r,   c                      e Zd ZdZdZd:dZd:dZed        Zd Z	d Z
e
Zd	 Zd
 Zd ZeZd Zd Zd Zd Zd Zd Zd Zd Zd ZeZd Zd Zd Zd Zd;dZd Z	 	 d<dZ d Z!d Z"d Z#e#Z$e#Z%d Z&d  Z'e'Z(d! Z)d" Z*d# Z+d=d$Z,d:d%Z-d& Z.e.Z/d' Z0d( Z1e1Z2d) Z3d* Z4 e4e5d+d,      Z6 e4e7d-d.      Z8 e4e9d/d0      Z: e4e;d1d2      Z< e4e=d3d4      Z> e4e?d5d6      Z@ eAe4      Z4d7 ZB eC       d8        ZDd9 ZEy)>
SortedLista  Sorted list is a sorted mutable sequence.

    Sorted list values are maintained in sorted order.

    Sorted list values must be comparable. The total ordering of values must
    not change while they are stored in the sorted list.

    Methods for adding values:

    * :func:`SortedList.add`
    * :func:`SortedList.update`
    * :func:`SortedList.__add__`
    * :func:`SortedList.__iadd__`
    * :func:`SortedList.__mul__`
    * :func:`SortedList.__imul__`

    Methods for removing values:

    * :func:`SortedList.clear`
    * :func:`SortedList.discard`
    * :func:`SortedList.remove`
    * :func:`SortedList.pop`
    * :func:`SortedList.__delitem__`

    Methods for looking up values:

    * :func:`SortedList.bisect_left`
    * :func:`SortedList.bisect_right`
    * :func:`SortedList.count`
    * :func:`SortedList.index`
    * :func:`SortedList.__contains__`
    * :func:`SortedList.__getitem__`

    Methods for iterating values:

    * :func:`SortedList.irange`
    * :func:`SortedList.islice`
    * :func:`SortedList.__iter__`
    * :func:`SortedList.__reversed__`

    Methods for miscellany:

    * :func:`SortedList.copy`
    * :func:`SortedList.__len__`
    * :func:`SortedList.__repr__`
    * :func:`SortedList._check`
    * :func:`SortedList._reset`

    Sorted lists use lexicographical ordering semantics when compared to other
    sequences.

    Some methods of mutable sequences are not supported and will raise
    not-implemented error.

    i  Nc                     |J d| _         | j                  | _        g | _        g | _        g | _        d| _        || j                  |       yy)a  Initialize sorted list instance.

        Optional `iterable` argument provides an initial iterable of values to
        initialize the sorted list.

        Runtime complexity: `O(n*log(n))`

        >>> sl = SortedList()
        >>> sl
        SortedList([])
        >>> sl = SortedList([3, 1, 2, 5, 4])
        >>> sl
        SortedList([1, 2, 3, 4, 5])

        :param iterable: initial values (optional)

        Nr   )_lenDEFAULT_LOAD_FACTOR_load_lists_maxes_index_offset_updater"   iterabler#   s      r(   __init__zSortedList.__init__   sU    $ {{	--
LL"  r,   c                     |t         j                  |       S | t        u rt         j                  t              S t	        d      )aJ  Create new sorted list or sorted-key list instance.

        Optional `key`-function argument will return an instance of subtype
        :class:`SortedKeyList`.

        >>> sl = SortedList()
        >>> isinstance(sl, SortedList)
        True
        >>> sl = SortedList(key=lambda x: -x)
        >>> isinstance(sl, SortedList)
        True
        >>> isinstance(sl, SortedKeyList)
        True

        :param iterable: initial values (optional)
        :param key: function used to extract comparison key (optional)
        :return: sorted list or sorted-key list instance

        z&inherit SortedKeyList for key argument)object__new__r0   SortedKeyList	TypeErrorclsr;   r#   s      r(   r?   zSortedList.__new__   s;    * ;>>#&&j ~~m44 HIIr,   c                      y)zFunction used to extract comparison key from values.

        Sorted list compares values directly so the key function is none.

        Nr-   r"   s    r(   r#   zSortedList.key   s     r,   c                     t        t        | j                  g       }| j                          || _        | j                  |       y)a  Reset sorted list load factor.

        The `load` specifies the load-factor of the list. The default load
        factor of 1000 works well for lists from tens to tens-of-millions of
        values. Good practice is to use a value that is the cube root of the
        list size. With billions of elements, the best load factor depends on
        your usage. It's best to leave the load factor at the default until you
        start benchmarking.

        See :doc:`implementation` and :doc:`performance-scale` for more
        information.

        Runtime complexity: `O(n)`

        :param int load: load-factor for sorted list sublists

        N)r   r   r5   _clearr4   r9   )r"   loadvaluess      r(   _resetzSortedList._reset   s2    $ dkk2.
Vr,   c                 z    d| _         | j                  dd= | j                  dd= | j                  dd= d| _        y)zQRemove all values from sorted list.

        Runtime complexity: `O(n)`

        r   N)r2   r5   r6   r7   r8   rE   s    r(   clearzSortedList.clear   s3     	KKNKKNKKNr,   c                 \   | j                   }| j                  }|rZt        ||      }|t        |      k(  r|dz  }||   j	                  |       |||<   nt        ||   |       | j                  |       n#|j	                  |g       |j	                  |       | xj                  dz  c_        y)a  Add `value` to sorted list.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList()
        >>> sl.add(3)
        >>> sl.add(1)
        >>> sl.add(2)
        >>> sl
        SortedList([1, 2, 3])

        :param value: value to add to sorted list

           N)r5   r6   r   lenappendr   _expandr2   )r"   valuer5   r6   poss        r(   r   zSortedList.add   s     vu-Cc&k!qs""5)#svc{E*LLMM5'"MM% 		Q	r,   c                    | j                   }| j                  }| j                  }t        ||         |dz  kD  rV| j                  }||   }||d }||d= |d   ||<   |j                  |dz   |       |j                  |dz   |d          |dd= y|r7| j                  |z   }|r||xx   dz  cc<   |dz
  dz	  }|r|dxx   dz  cc<   yya>  Split sublists with length greater than double the load-factor.

        Updates the index when the sublist length is less than double the load
        level. This requires incrementing the nodes in a traversal from the
        leaf node to the root. For an example traversal see
        ``SortedList._loc``.

        rN   Nr   )r4   r5   r7   rO   r6   insertr8   )	r"   rS   r4   r5   r7   r6   
_lists_poshalfchilds	            r(   rQ   zSortedList._expand!  s     

vc{uz*[[FJef%D56"$R.F3KMM#'4(MM#'48,q	s*5MQ&M"QY1,E  q	Q	 r,   c           	      *   | j                   }| j                  }t        |      |rzt              dz  | j                  k\  rC|j                         t        t        |g       j                          | j                          n| j                  }D ]
  } ||        y| j                  |j                  fdt        dt                    D               |j                  d |D               t              | _        | j                  dd= y)a  Update sorted list by adding all values from `iterable`.

        Runtime complexity: `O(k*log(n))` -- approximate.

        >>> sl = SortedList()
        >>> sl.update([3, 1, 2])
        >>> sl
        SortedList([1, 2, 3])

        :param iterable: iterable of values to add

           Nc              3   .   K   | ]  }||z      y wr   r-   .0rS   r4   rI   s     r(   	<genexpr>z$SortedList.update.<locals>.<genexpr>a  $      ? S#+/ ?   r   c              3   &   K   | ]	  }|d      ywrV   Nr-   r_   sublists     r(   r`   z$SortedList.update.<locals>.<genexpr>c  s     8ggbk8   )r5   r6   sortedrO   r2   rP   r   r   sortrG   r   r4   extendranger7   )r"   r;   r5   r6   _addvalr4   rI   s         @@r(   updatezSortedList.updateC  s     !6{Q$))+f%fb1xx! CI

 ?!&q#f+u!=? 	?888K	KKNr,   c                     | j                   }|syt        ||      }|t        |      k(  ry| j                  }t        ||   |      }||   |   |k(  S )aZ  Return true if `value` is an element of the sorted list.

        ``sl.__contains__(value)`` <==> ``value in sl``

        Runtime complexity: `O(log(n))`

        >>> sl = SortedList([1, 2, 3, 4, 5])
        >>> 3 in sl
        True

        :param value: search for value in sorted list
        :return: true if `value` in sorted list

        F)r6   r   rO   r5   r"   rR   r6   rS   r5   idxs         r(   __contains__zSortedList.__contains__j  s[     &%(#f+&+u-c{35((r,   c                     | j                   }|syt        ||      }|t        |      k(  ry| j                  }t        ||   |      }||   |   |k(  r| j	                  ||       yy)ao  Remove `value` from sorted list if it is a member.

        If `value` is not a member, do nothing.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList([1, 2, 3, 4, 5])
        >>> sl.discard(5)
        >>> sl.discard(0)
        >>> sl == [1, 2, 3, 4]
        True

        :param value: `value` to discard from sorted list

        N)r6   r   rO   r5   _deleterp   s         r(   r!   zSortedList.discard  sk      &%(#f+&+u-#;su$LLc" %r,   c                 `   | j                   }|st        dj                  |            t        ||      }|t	        |      k(  rt        dj                  |            | j
                  }t        ||   |      }||   |   |k(  r| j                  ||       yt        dj                  |            )a  Remove `value` from sorted list; `value` must be a member.

        If `value` is not a member, raise ValueError.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList([1, 2, 3, 4, 5])
        >>> sl.remove(5)
        >>> sl == [1, 2, 3, 4]
        True
        >>> sl.remove(0)
        Traceback (most recent call last):
          ...
        ValueError: 0 not in list

        :param value: `value` to remove from sorted list
        :raises ValueError: if `value` is not in sorted list

        {0!r} not in listN)r6   
ValueErrorformatr   rO   r5   rt   rp   s         r(   removezSortedList.remove  s    ( 077>??&%(#f+077>??&+u-#;su$LLc"077>??r,   c                 .   | j                   }| j                  }| j                  }||   }||= | xj                  dz  c_        t	        |      }|| j
                  dz	  kD  rH|d   ||<   |r=| j                  |z   }|dkD  r||xx   dz  cc<   |dz
  dz	  }|dkD  r|dxx   dz  cc<   yyt	        |      dkD  rK|s|dz  }|dz
  }	||	   j                  ||          ||	   d   ||	<   ||= ||= |dd= | j                  |	       y|r	|d   ||<   y||= ||= |dd= ya  Delete value at the given `(pos, idx)`.

        Combines lists that are less than half the load level.

        Updates the index when the sublist length is more than half the load
        level. This requires decrementing the nodes in a traversal from the
        leaf node to the root. For an example traversal see
        ``SortedList._loc``.

        :param int pos: lists index
        :param int idx: sublist index

        rN   rV   r   N)	r5   r6   r7   r2   rO   r4   r8   rj   rQ   )
r"   rS   rq   r5   r6   r7   rX   len_lists_posrZ   prevs
             r(   rt   zSortedList._delete  sC    C[
sO		Q	JDJJ!O,$R.F3Ks*ai5MQ&M"QY1,E ai q	Q	  [1_q7D4Ls,!$<+F4Lssq	LL$R.F3Kssq	r,   c                     |s|S | j                   }|s| j                          d}|| j                  z  }|r|dz  s|||dz
     z  }|dz
  dz	  }|r||z   S )a  Convert an index pair (lists index, sublist index) into a single
        index number that corresponds to the position of the value in the
        sorted list.

        Many queries require the index be built. Details of the index are
        described in ``SortedList._build_index``.

        Indexing requires traversing the tree from a leaf node to the root. The
        parent of each node is easily computable at ``(pos - 1) // 2``.

        Left-child nodes are always at odd indices and right-child nodes are
        always at even indices.

        When traversing up from a right-child node, increment the total by the
        left-child node.

        The final index is the sum from traversal and the index in the sublist.

        For example, using the index from ``SortedList._build_index``::

            _index = 14 5 9 3 2 4 5
            _offset = 3

        Tree::

                 14
              5      9
            3   2  4   5

        Converting an index pair (2, 3) into a single index involves iterating
        like so:

        1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
           the node as a left-child node. At such nodes, we simply traverse to
           the parent.

        2. At node 9, position 2, we recognize the node as a right-child node
           and accumulate the left-child in our total. Total is now 5 and we
           traverse to the parent at position 0.

        3. Iteration ends at the root.

        The index is then the sum of the total and sublist index: 5 + 3 = 8.

        :param int pos: lists index
        :param int idx: sublist index
        :return: index in sorted list

        r   rN   )r7   _build_indexr8   )r"   rS   rq   r7   totals        r(   _loczSortedList._loc  sz    d J 	t|| 
 7a( 7q.C  s{r,   c                    |dk  rZt        | j                  d         }| |k  rt        | j                        dz
  ||z   fS || j                  z  }|dk  r%t        d      || j                  k\  rt        d      |t        | j                  d         k  rd|fS | j                  }|s| j                          d}d}t        |      }||k  r%||   }||k  r|}n
||z  }|dz   }|dz  dz   }||k  r%|| j                  z
  |fS )ai  Convert an index into an index pair (lists index, sublist index)
        that can be used to access the corresponding lists position.

        Many queries require the index be built. Details of the index are
        described in ``SortedList._build_index``.

        Indexing requires traversing the tree to a leaf node. Each node has two
        children which are easily computable. Given an index, pos, the
        left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +
        2``.

        When the index is less than the left-child, traversal moves to the
        left sub-tree. Otherwise, the index is decremented by the left-child
        and traversal moves to the right sub-tree.

        At a child node, the indexing pair is computed from the relative
        position of the child node as compared with the offset and the remaining
        index.

        For example, using the index from ``SortedList._build_index``::

            _index = 14 5 9 3 2 4 5
            _offset = 3

        Tree::

                 14
              5      9
            3   2  4   5

        Indexing position 8 involves iterating like so:

        1. Starting at the root, position 0, 8 is compared with the left-child
           node (5) which it is greater than. When greater the index is
           decremented and the position is updated to the right child node.

        2. At node 9 with index 3, we again compare the index to the left-child
           node with value 4. Because the index is the less than the left-child
           node, we simply traverse to the left.

        3. At node 4 with index 3, we recognize that we are at a leaf node and
           stop iterating.

        4. To compute the sublist index, we subtract the offset from the index
           of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we
           simply use the index remaining from iteration. In this case, 3.

        The final index pair from our example is (2, 3) which corresponds to
        index 8 in the sorted list.

        :param int idx: index in sorted list
        :return: (lists index, sublist index) pair

        r   rV   rN   list index out of range)rO   r5   r2   
IndexErrorr7   r   r8   )r"   rq   last_lenr7   rS   rZ   	len_indexindex_childs           r(   _poszSortedList._posY  s%   n 74;;r?+H!4;;'!+X^;;499CQw !:;;DII677T[[^$$c6MK	i -K[ {"aiAXNE i dll"C((r,   c           	         t        t        t        | j                              }t        |      dk(  r|| j                  dd d| _        yt        |      }t        |      }t        t        t        t        ||                  }t        |      dz  r|j                  |d          t        |      dk(  r||z   | j                  dd d| _        ydt        t        t        |      dz
  d            dz   z  }|j                  t        d|t        |      z
               ||g}t        |d         dkD  r_t        |d         }t        |      }t        t        t        t        ||                  }|j                  |       t        |d         dkD  r_t        t         t#        |      | j                         |dz  dz
  | _        y)a  Build a positional index for indexing the sorted list.

        Indexes are represented as binary trees in a dense array notation
        similar to a binary heap.

        For example, given a lists representation storing integers::

            0: [1, 2, 3]
            1: [4, 5]
            2: [6, 7, 8, 9]
            3: [10, 11, 12, 13, 14]

        The first transformation maps the sub-lists by their length. The
        first row of the index is the length of the sub-lists::

            0: [3, 2, 4, 5]

        Each row after that is the sum of consecutive pairs of the previous
        row::

            1: [5, 9]
            2: [14]

        Finally, the index is built by concatenating these lists together::

            _index = [14, 5, 9, 3, 2, 4, 5]

        An offset storing the start of the first row is also stored::

            _offset = 3

        When built, the index can be used for efficient indexing into the list.
        See the comment and notes on ``SortedList._pos`` for details.

        rN   Nr   rV      )listmaprO   r5   r7   r8   iterr	   r   ziprP   intr
   rj   r   r   r   reversed)r"   row0headtailrow1sizetreerows           r(   r   zSortedList._build_index  sn   H CT[[)*t9>!DKKNDLDzDzGCT412t9q=KKR!t9>!D[DKKNDLSSY]A./!34F1dSY./0d|$r(maR>D:DwsCdO45CKK	 $r(ma 	tXd^T[[1ax!|r,   c                    t        |t              r|j                  | j                        \  }}}|dk(  r||k  r|dk(  r|| j                  k(  r| j	                         S | j                  d||z
  z  k  ri| j                  t        d|            }|| j                  k  r|| j                  t        |d            z  }| j	                          | j                  |      S t        |||      }|dkD  rt        |      }| j                  | j                  }}|D ]  } ||      \  }	}
 ||	|
        y| j                  |      \  }	}
| j                  |	|
       y)a  Remove value at `index` from sorted list.

        ``sl.__delitem__(index)`` <==> ``del sl[index]``

        Supports slicing.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList('abcde')
        >>> del sl[2]
        >>> sl
        SortedList(['a', 'b', 'd', 'e'])
        >>> del sl[:2]
        >>> sl
        SortedList(['d', 'e'])

        :param index: integer or slice for indexing
        :raises IndexError: if index out of range

        rN   r      N)
isinstancesliceindicesr2   rG   _getitemr9   rk   r   r   rt   )r"   indexstartstopsteprI   r   r   rt   rS   rq   s              r(   __delitem__zSortedList.__delitem__  s4   * eU# %dii 8E4qyUT\A:$$))"3;;=(YY!te|"44!]]5u+=>Fdii'$--dD0A"BBKKM<<//E4.G
 ax"7+ IIt||'D  ";SS!" yy'HCLLc"r,   c                      j                   }t        |t              rX|j                   j                        \  }}}|dk(  r||k  r|dk(  r*| j                  k(  rt        t         j                   g       S  j                  |      \  }}||   }||z   |z
  }	t        |      |	k\  r|||	 S | j                  k(  rt        |      dz
  }
t        ||
         }	n j                  |      \  }
}	||   |d }||dz   |
 }t        t        ||      }|||
   d|	 z  }|S |dk(  r8||kD  r3 j                  t        |dz   |dz               }|j                          |S t        |||      }t         fd|D              S  j                  r|dk(  r|d   d   S |dk(  r|d   d   S t        d      d|cxk  rt        |d         k  rn n|d   |   S t        |d         }| |cxk  rdk  rn n|d   ||z      S  j                  |      \  }}||   |   S )a  Lookup value at `index` in sorted list.

        ``sl.__getitem__(index)`` <==> ``sl[index]``

        Supports slicing.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList('abcde')
        >>> sl[1]
        'b'
        >>> sl[-1]
        'e'
        >>> sl[2:5]
        ['c', 'd', 'e']

        :param index: integer or slice for indexing
        :return: value or list of values
        :raises IndexError: if index out of range

        rN   r   NrV   c              3   @   K   | ]  }j                  |        y wr   )r   )r_   r   r"   s     r(   r`   z)SortedList.__getitem__.<locals>.<genexpr>s  s     Be,Bs   r   )r5   r   r   r   r2   r   r   r   rO   r   reverserk   r   r   )r"   r   r5   r   r   r   	start_pos	start_idx
start_liststop_idxstop_posprefixmiddler$   r   len_lastrS   rq   s   `                 r(   __getitem__zSortedList.__getitem__0  s<   , eU# %dii 8E4qyUT\ A:$$))"3!$R88'+yy'7$	9#I.
$t+e3
 z?h.%i99499$"6{QH"6(#34H)-4&Hh	*9:6Q9ff5&*9H55rzedluTAXuqy'AB  E4.GB'BBByyA:!!9Q<'b[!":b>) !:;;E*Cq	N*ay''6":Hy5$1$bz(U"233yy'HC#;s##r,   c                     d}t        |      )zRaise not-implemented error.

        ``sl.__setitem__(index, value)`` <==> ``sl[index] = value``

        :raises NotImplementedError: use ``del sl[index]`` and
            ``sl.add(value)`` instead

        z3use ``del sl[index]`` and ``sl.add(value)`` insteadNotImplementedError)r"   r   rR   messages       r(   __setitem__zSortedList.__setitem__  s     H!'**r,   c                 @    t        j                  | j                        S )zReturn an iterator over the sorted list.

        ``sl.__iter__()`` <==> ``iter(sl)``

        Iterating the sorted list while adding or deleting values may raise a
        :exc:`RuntimeError` or fail to iterate over all values.

        )r   from_iterabler5   rE   s    r(   __iter__zSortedList.__iter__  s     ""4;;//r,   c                 n    t        j                  t        t        t        | j                                    S )zReturn a reverse iterator over the sorted list.

        ``sl.__reversed__()`` <==> ``reversed(sl)``

        Iterating the sorted list while adding or deleting values may raise a
        :exc:`RuntimeError` or fail to iterate over all values.

        )r   r   r   r   r5   rE   s    r(   __reversed__zSortedList.__reversed__  s%     ""3x$++1F#GHHr,   c                     t        d      )a  Raise not-implemented error.

        Sorted list maintains values in ascending sort order. Values may not be
        reversed in-place.

        Use ``reversed(sl)`` for an iterator over values in descending sort
        order.

        Implemented to override `MutableSequence.reverse` which provides an
        erroneous default implementation.

        :raises NotImplementedError: use ``reversed(sl)`` instead

        zuse ``reversed(sl)`` insteadr   rE   s    r(   r   zSortedList.reverse  s     ""@AAr,   c                    | j                   }|st        d      S t        ||      j                  | j                         \  }}}||k\  rt        d      S | j                  } ||      \  }}||k(  r1t        | j                        dz
  }	t        | j                  d         }
n ||      \  }	}
| j                  |||	|
|      S )a  Return an iterator that slices sorted list from `start` to `stop`.

        The `start` and `stop` index are treated inclusive and exclusive,
        respectively.

        Both `start` and `stop` default to `None` which is automatically
        inclusive of the beginning and end of the sorted list.

        When `reverse` is `True` the values are yielded from the iterator in
        reverse order; `reverse` defaults to `False`.

        >>> sl = SortedList('abcdefghij')
        >>> it = sl.islice(2, 6)
        >>> list(it)
        ['c', 'd', 'e', 'f']

        :param int start: start index (inclusive)
        :param int stop: stop index (exclusive)
        :param bool reverse: yield values in reverse order
        :return: iterator

        r-   rN   rV   )r2   r   r   r   r   rO   r5   _islice)r"   r   r   r   r2   _r   min_posmin_idxmax_posmax_idxs              r(   islicezSortedList.islice  s    . yy8Oud+33DII>tQD=8Oyy;4<$++&*G$++b/*G#DzGW||GWgwHHr,   c           
      @   | j                   }||kD  rt        d      S ||k(  rU|r.t        t        ||            }t	        ||   j
                  |      S t        ||      }t	        ||   j
                  |      S |dz   }||k(  r|rot        |t        ||               }	t        |      }
t        t	        ||   j
                  t        |
            t	        ||   j
                  t        |	                  S t        |t        ||               }	t        |      }
t        t	        ||   j
                  |	      t	        ||   j
                  |
            S |rt        |t        ||               }	t        ||      }t	        |j
                  t        |            }t        |      }
t        t	        ||   j
                  t        |
            t        j                  t	        t        |            t	        ||   j
                  t        |	                  S t        |t        ||               }	t        ||      }t	        |j
                  |      }t        |      }
t        t	        ||   j
                  |	      t        j                  |      t	        ||   j
                  |
            S )ay  Return an iterator that slices sorted list using two index pairs.

        The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the
        first inclusive and the latter exclusive. See `_pos` for details on how
        an index is converted to an index pair.

        When `reverse` is `True`, values are yielded from the iterator in
        reverse order.

        r-   rN   )	r5   r   r   rk   r   r   rO   r   r   )r"   r   r   r   r   r   r5   r   next_posmin_indicesmax_indicessublist_indicessublistss                r(   r   zSortedList._islice  sU    W8Og"5'#:;6'?66@@GW-Gvg22G<<Q;w#GS-AB#Gnw33Xk5JKw33Xk5JK 
  VG_)=>K.KF7O//=F7O//= 
 VG_)=>K#Hg6O6--x/HIH.KF7O//+1FG##C($;<F7O//+1FG  GS%9:'2v))?;Gnw++[9)w++[9
 	
r,   c                    | j                   }|st        d      S | j                  }|d}d}nn|d   r5t        ||      }|t	        |      k(  rt        d      S t        ||   |      }n4t        ||      }|t	        |      k(  rt        d      S t        ||   |      }|t	        |      dz
  }	t	        ||	         }
n|d   r>t        ||      }	|	t	        |      k(  r|	dz  }	t	        ||	         }
nMt        ||	   |      }
n=t        ||      }	|	t	        |      k(  r|	dz  }	t	        ||	         }
nt        ||	   |      }
| j                  |||	|
|      S )a  Create an iterator of values between `minimum` and `maximum`.

        Both `minimum` and `maximum` default to `None` which is automatically
        inclusive of the beginning and end of the sorted list.

        The argument `inclusive` is a pair of booleans that indicates whether
        the minimum and maximum ought to be included in the range,
        respectively. The default is ``(True, True)`` such that the range is
        inclusive of both minimum and maximum.

        When `reverse` is `True` the values are yielded from the iterator in
        reverse order; `reverse` defaults to `False`.

        >>> sl = SortedList('abcdefghij')
        >>> it = sl.irange('c', 'f')
        >>> list(it)
        ['c', 'd', 'e', 'f']

        :param minimum: minimum value to start iterating
        :param maximum: maximum value to stop iterating
        :param inclusive: pair of booleans
        :param bool reverse: yield values in reverse order
        :return: iterator

        r-   r   rN   )r6   r   r5   r   rO   r   r   )r"   minimummaximum	inclusiver   r6   r5   r   r   r   r   s              r(   irangezSortedList.irange0  sZ   6 8O
 ?GG|%fg6c&k)8O%fWow?&vw7c&k)8O&vg@
 ?&kAoG&/*G|&vw7c&k)qLG!&/2G*6'?GDG%fg6c&k)qLG!&/2G)&/7CG||GWgwHHr,   c                     | j                   S )z~Return the size of the sorted list.

        ``sl.__len__()`` <==> ``len(sl)``

        :return: size of sorted list

        )r2   rE   s    r(   __len__zSortedList.__len__  s     yyr,   c                     | j                   }|syt        ||      }|t        |      k(  r| j                  S t        | j                  |   |      }| j                  ||      S )a  Return an index to insert `value` in the sorted list.

        If the `value` is already present, the insertion point will be before
        (to the left of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList([10, 11, 12, 13, 14])
        >>> sl.bisect_left(12)
        2

        :param value: insertion index of value in sorted list
        :return: index

        r   )r6   r   rO   r2   r5   r   r"   rR   r6   rS   rq   s        r(   r   zSortedList.bisect_left  s[    $ &%(#f+99$++c*E2yyc""r,   c                     | j                   }|syt        ||      }|t        |      k(  r| j                  S t        | j                  |   |      }| j                  ||      S )a  Return an index to insert `value` in the sorted list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point will be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList([10, 11, 12, 13, 14])
        >>> sl.bisect_right(12)
        3

        :param value: insertion index of value in sorted list
        :return: index

        r   )r6   r   rO   r2   r5   r   r   s        r(   r   zSortedList.bisect_right  s[    $ 65)#f+994;;s+U3yyc""r,   c                    | j                   }|syt        ||      }|t        |      k(  ry| j                  }t        ||   |      }t	        ||      }|t        |      k(  r| j
                  | j                  ||      z
  S t	        ||   |      }||k(  r||z
  S | j                  ||      }| j                  ||      }	||	z
  S )a)  Return number of occurrences of `value` in the sorted list.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
        >>> sl.count(3)
        3

        :param value: value to count in sorted list
        :return: count

        r   )r6   r   rO   r5   r   r2   r   )
r"   rR   r6   pos_leftr5   idx_left	pos_right	idx_rightrightlefts
             r(   countzSortedList.count  s     vu-s6{"vh/7 /	F#99tyy8<<< 	!2E:	y x''		)Y/yy8,t|r,   c                 $    | j                  |       S )zyReturn a shallow copy of the sorted list.

        Runtime complexity: `O(n)`

        :return: new sorted list

        )	__class__rE   s    r(   copyzSortedList.copy  s     ~~d##r,   c                     t        d      )zRaise not-implemented error.

        Implemented to override `MutableSequence.append` which provides an
        erroneous default implementation.

        :raises NotImplementedError: use ``sl.add(value)`` instead

        use ``sl.add(value)`` insteadr   r"   rR   s     r(   rP   zSortedList.append  s     ""ABBr,   c                     t        d      )zRaise not-implemented error.

        Implemented to override `MutableSequence.extend` which provides an
        erroneous default implementation.

        :raises NotImplementedError: use ``sl.update(values)`` instead

        z!use ``sl.update(values)`` insteadr   r"   rI   s     r(   rj   zSortedList.extend  s     ""EFFr,   c                     t        d      )zjRaise not-implemented error.

        :raises NotImplementedError: use ``sl.add(value)`` instead

        r   r   )r"   r   rR   s      r(   rW   zSortedList.insert  s     ""ABBr,   c                 n   | j                   st        d      | j                  }|dk(  r|d   d   }| j                  dd       |S |dk(  r;t	        |      dz
  }t	        ||         dz
  }||   |   }| j                  ||       |S d|cxk  rt	        |d         k  rn n|d   |   }| j                  d|       |S t	        |d         }| |cxk  rdk  r2n n/t	        |      dz
  }||z   }||   |   }| j                  ||       |S | j                  |      \  }}||   |   }| j                  ||       |S )a  Remove and return value at `index` in sorted list.

        Raise :exc:`IndexError` if the sorted list is empty or index is out of
        range.

        Negative indices are supported.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList('abcde')
        >>> sl.pop()
        'e'
        >>> sl.pop(2)
        'c'
        >>> sl
        SortedList(['a', 'b', 'd'])

        :param int index: index of value (default -1)
        :return: value
        :raises IndexError: if index is out of range

        zpop index out of ranger   rV   rN   )r2   r   r5   rt   rO   r   )r"   r   r5   rm   rS   locr   rq   s           r(   popzSortedList.pop'  sL   . yy566A:)A,CLLAJB;f+/CfSk"Q&C+c"CLLc"J&F1I&)E"CLLE"Jvbz?9u q f+/CU"C+c"CLLc"J99U#SSk#S#
r,   c                    | j                   }|st        dj                  |            |d}|dk  r||z  }|dk  rd}||}|dk  r||z  }||kD  r|}||k  rt        dj                  |            | j                  }t	        ||      }|t        |      k(  rt        dj                  |            | j                  }t	        ||   |      }||   |   |k7  rt        dj                  |            |dz  }| j                  ||      }	||	k  r|	|k  r|	S | j                  |      dz
  }
||
k  r|S t        dj                  |            )aq  Return first index of value in sorted list.

        Raise ValueError if `value` is not present.

        Index must be between `start` and `stop` for the `value` to be
        considered present. The default value, None, for `start` and `stop`
        indicate the beginning and end of the sorted list.

        Negative indices are supported.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> sl = SortedList('abcde')
        >>> sl.index('d')
        3
        >>> sl.index('z')
        Traceback (most recent call last):
          ...
        ValueError: 'z' is not in list

        :param value: value in sorted list
        :param int start: start index (default None, start of sorted list)
        :param int stop: stop index (default None, end of sorted list)
        :return: index of value
        :raises ValueError: if value is not present

        {0!r} is not in listr   rN   )	r2   rw   rx   r6   r   rO   r5   r   _bisect_right)r"   rR   r   r   r2   r6   r   r5   r   r   r   s              r(   r   zSortedList.indexc  sp   8 yy3::5ABB=E19TME19E<D!8DLD$;D5=3::5ABBvu-s6{"3::5ABBvh/7(H%.3::5ABB	yy8,D=t|&&u-1E~/66u=>>r,   c                 |    t        t        | j                  g       }|j                  |       | j	                  |      S )a  Return new sorted list containing all values in both sequences.

        ``sl.__add__(other)`` <==> ``sl + other``

        Values in `other` do not need to be in sorted order.

        Runtime complexity: `O(n*log(n))`

        >>> sl1 = SortedList('bat')
        >>> sl2 = SortedList('cat')
        >>> sl1 + sl2
        SortedList(['a', 'a', 'b', 'c', 't', 't'])

        :param other: other iterable
        :return: new sorted list

        )r   r   r5   rj   r   r"   otherrI   s      r(   __add__zSortedList.__add__  s1    $ dkk2.e~~f%%r,   c                 (    | j                  |       | S )a  Update sorted list with values from `other`.

        ``sl.__iadd__(other)`` <==> ``sl += other``

        Values in `other` do not need to be in sorted order.

        Runtime complexity: `O(k*log(n))` -- approximate.

        >>> sl = SortedList('bat')
        >>> sl += 'cat'
        >>> sl
        SortedList(['a', 'a', 'b', 'c', 't', 't'])

        :param other: other iterable
        :return: existing sorted list

        )r9   )r"   r   s     r(   __iadd__zSortedList.__iadd__  s    $ 	Ur,   c                 `    t        t        | j                  g       |z  }| j                  |      S )aj  Return new sorted list with `num` shallow copies of values.

        ``sl.__mul__(num)`` <==> ``sl * num``

        Runtime complexity: `O(n*log(n))`

        >>> sl = SortedList('abc')
        >>> sl * 3
        SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])

        :param int num: count of shallow copies
        :return: new sorted list

        )r   r   r5   r   r"   numrI   s      r(   __mul__zSortedList.__mul__  s*     dkk2.4~~f%%r,   c                     t        t        | j                  g       |z  }| j                          | j	                  |       | S )a  Update the sorted list with `num` shallow copies of values.

        ``sl.__imul__(num)`` <==> ``sl *= num``

        Runtime complexity: `O(n*log(n))`

        >>> sl = SortedList('abc')
        >>> sl *= 3
        >>> sl
        SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])

        :param int num: count of shallow copies
        :return: existing sorted list

        )r   r   r5   rG   r9   r   s      r(   __imul__zSortedList.__imul__  s5      dkk2.4Vr,   c                       fd} j                   }dj                  |      |_         d}t        |j                  |||            |_        |S )zMake comparator method.c                     t        |t              st        S | j                  }t	        |      }||k7  rt
        u ryt        u ryt        | |      D ]  \  }}||k7  s ||      c S   ||      S )z,Compare method for sorted list and sequence.FT)r   r   NotImplementedr2   rO   r   r   r   )r"   r   self_len	len_otheralphabetaseq_ops         r(   comparerz'SortedList.__make_cmp.<locals>.comparer  s~    eX.%%yyHE
I9$R< R<"4/ /tD=!%../ (I..r,   z__{0}__a7  Return true if and only if sorted list is {0} `other`.

        ``sl.__{1}__(other)`` <==> ``sl {2} other``

        Comparisons use lexicographical order as with sequences.

        Runtime complexity: `O(n)`

        :param other: `other` sequence
        :return: true if sorted list is {0} `other`

        )__name__rx   r   __doc__)r   symboldocr   seq_op_namedoc_strs   `     r(   
__make_cmpzSortedList.__make_cmp
  sN    	/( oo%,,[9 "'..k6"JKr,   z==zequal toz!=znot equal to<z	less than>zgreater thanz<=zless than or equal toz>=zgreater than or equal toc                 T    t        t        | j                  g       }t        |       |ffS r   )r   r   r5   typer   s     r(   
__reduce__zSortedList.__reduce__;  s%    dkk2.T
VI&&r,   c                 ^    dj                  t        |       j                  t        |             S )zReturn string representation of sorted list.

        ``sl.__repr__()`` <==> ``repr(sl)``

        :return: string representation

        z
{0}({1!r}))rx   r  r   r   rE   s    r(   __repr__zSortedList.__repr__@  s%     ""4:#6#6T
CCr,   c                    	 | j                   dk\  sJ t        | j                        t        | j                        k(  sJ | j                  t        d | j                  D              k(  sJ | j                  D ],  }t        dt        |            D ]  }||dz
     ||   k  rJ  . t        dt        | j                              D ],  }| j                  |dz
     d   | j                  |   d   k  r,J  t        t        | j                              D ]&  }| j                  |   | j                  |   d   k(  r&J  | j                   dz  t        fd| j                  D              sJ | j                   dz	  }t        dt        | j                        dz
        D ]  }t        | j                  |         |k\  rJ  | j                  rw| j                  | j                  d   k(  sJ t        | j                        | j                  t        | j                        z   k(  sJ t        t        | j                              D ];  }| j                  | j                  |z      }|t        | j                  |         k(  r;J  t        | j                        D ]  }|dz  dz   }|t        | j                        k\  r| j                  |   dk(  r6J |dz   t        | j                        k(  r"| j                  |   | j                  |   k(  rsJ | j                  |   | j                  |dz      z   }|| j                  |   k(  rJ  yy#  t        j                  t        j                         t        d| j                         t        d	| j                          t        d
| j                         t        dt        | j                               t        d| j                         t        dt        | j                               t        d| j                         t        dt        | j                               t        d| j                          xY w)zNCheck invariants of sorted list.

        Runtime complexity: `O(n)`

        r\   c              3   2   K   | ]  }t        |        y wr   rO   re   s     r(   r`   z$SortedList._check.<locals>.<genexpr>U       #LWCL#L   rN   rV   r   c              3   :   K   | ]  }t        |      k    y wr   r  r_   rf   doubles     r(   r`   z$SortedList._check.<locals>.<genexpr>j       I's7|v-I   filerO   rH   offsetr   r   	len_maxesmaxes	len_listslistsN)r4   rO   r6   r5   r2   sumrk   allr7   r8   	traceback	print_excsysstdoutprint)r"   rf   rS   rY   leafrZ   	child_sumr  s          @r(   _checkzSortedList._checkL  s   A	::?"?t{{#s4;;'777799#L#L LLLL  ;; < CL1 <C"37+ws|;;;<< QDKK 01 G{{37+B/4;;s3CA3FFFFG
 S-. @{{3'4;;s+;B+????@
 ZZ1_FIT[[IIII
 ::?DQDKK 01 45 54;;s+,4445 {{yyDKKN2224;;'4<<#dkk:J+JJJJ !T[[!12 9C;;t||c'9:D3t{{3'7#88889 !. =C AXNEDKK 00#{{3/1444c$++&66#{{3/4;;u3EEEE$(KK$6UQY9O$O	(DKK,<<<<= *	SZZ0%#&$**%(DLL)+s4;;/0'4;;'+s4;;/0'4;;'+s4;;/0'4;;'sB   BM "AM 2AM 9BM ;C M <AM 
<M 6M >M DQNN)NNFNN)TTF)rV   )Fr   
__module____qualname__r   r3   r<   r?   propertyr#   rJ   rL   rG   r   rQ   rn   r9   rr   r!   ry   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   bisectr   r   r   __copy__rP   rj   rW   r   r   r   __radd__r   r   __rmul__r   _SortedList__make_cmpr   __eq__r   __ne__r   __lt__r   __gt__r   __le__r   __ge__staticmethodr	  r.   r  r&  r-   r,   r(   r0   r0   U   s   6n #<J<  0
 F!HD"H G)>#B$@N4nNb[)|B$J1#hV$p H
+	0	IB$+I\=
@ <HPIf#@#> F M%P$ H	C	GC9xJ?Z&, H,&$ H,%P D*-FD.1FC-FC0FD"9:FD"<=Fj)J'
 D DGr,   r0   c                     | S )zIdentity function.r-   )rR   s    r(   identityr9    s    Lr,   c                      e Zd ZdZdefdZdefdZed        Zd Z	e	Z
d Zd Zd	 ZeZd
 Zd Zd Zd Z	 	 ddZ	 	 ddZeZd Zd ZeZd ZeZd ZeZeZd Zd ZeZ ddZ!d Z"e"Z#d Z$d Z% e&       d        Z'd Z(y)r@   ai  Sorted-key list is a subtype of sorted list.

    The sorted-key list maintains values in comparison order based on the
    result of a key function applied to every value.

    All the same methods that are available in :class:`SortedList` are also
    available in :class:`SortedKeyList`.

    Additional methods provided:

    * :attr:`SortedKeyList.key`
    * :func:`SortedKeyList.bisect_key_left`
    * :func:`SortedKeyList.bisect_key_right`
    * :func:`SortedKeyList.irange_key`

    Some examples below use:

    >>> from operator import neg
    >>> neg
    <built-in function neg>
    >>> neg(1)
    -1

    Nc                     || _         d| _        | j                  | _        g | _        g | _        g | _        g | _        d| _        || j                  |       yy)a6  Initialize sorted-key list instance.

        Optional `iterable` argument provides an initial iterable of values to
        initialize the sorted-key list.

        Optional `key` argument defines a callable that, like the `key`
        argument to Python's `sorted` function, extracts a comparison key from
        each value. The default is the identity function.

        Runtime complexity: `O(n*log(n))`

        >>> from operator import neg
        >>> skl = SortedKeyList(key=neg)
        >>> skl
        SortedKeyList([], key=<built-in function neg>)
        >>> skl = SortedKeyList([3, 1, 2], key=neg)
        >>> skl
        SortedKeyList([3, 2, 1], key=<built-in function neg>)

        :param iterable: initial values (optional)
        :param key: function used to extract comparison key (optional)

        r   N)
_keyr2   r3   r4   r5   _keysr6   r7   r8   r9   r:   s      r(   r<   zSortedKeyList.__init__  sY    0 		--

LL"  r,   c                 ,    t         j                  |       S r   )r>   r?   rB   s      r(   r?   zSortedKeyList.__new__  s    ~~c""r,   c                     | j                   S )z4Function used to extract comparison key from values.)r<  rE   s    r(   r#   zSortedKeyList.key  s     yyr,   c                     d| _         | j                  dd= | j                  dd= | j                  dd= | j                  dd= y)zURemove all values from sorted-key list.

        Runtime complexity: `O(n)`

        r   N)r2   r5   r=  r6   r7   rE   s    r(   rL   zSortedKeyList.clear  s7     	KKNJJqMKKNKKNr,   c                 6   | j                   }| j                  }| j                  }| j                  |      }|rt	        ||      }|t        |      k(  r3|dz  }||   j                  |       ||   j                  |       |||<   n9t	        ||   |      }||   j                  ||       ||   j                  ||       | j                  |       n5|j                  |g       |j                  |g       |j                  |       | xj                  dz  c_	        y)a{  Add `value` to sorted-key list.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList(key=neg)
        >>> skl.add(3)
        >>> skl.add(1)
        >>> skl.add(2)
        >>> skl
        SortedKeyList([3, 2, 1], key=<built-in function neg>)

        :param value: value to add to sorted-key list

        rN   N)
r5   r=  r6   r<  r   rO   rP   rW   rQ   r2   )r"   rR   r5   r=  r6   r#   rS   rq   s           r(   r   zSortedKeyList.add  s      

iivs+Cc&k!qs""5)c
!!#&!s"5:s3s""3.c
!!#s+LLMM5'"LL#MM#		Q	r,   c                    | j                   }| j                  }| j                  }t        ||         | j                  dz  kD  r| j
                  }| j                  }||   }||   }||d }	||d }
||d= ||d= |d   ||<   |j                  |dz   |	       |j                  |dz   |
       |j                  |dz   |
d          |dd= y|r7| j                  |z   }|r||xx   dz  cc<   |dz
  dz	  }|r|dxx   dz  cc<   yyrU   )r5   r=  r7   rO   r4   r6   rW   r8   )r"   rS   r5   r=  r7   r6   r4   rX   	_keys_posrY   	half_keysrZ   s               r(   rQ   zSortedKeyList._expand  s    

uSz?djjAo.[[FJJEJc
Ief%D!%&)I56"%&!#B-F3KMM#'4(LLq),MM#'9R=1q	s*5MQ&M"QY1,E  q	Q	 r,   c           	           j                   } j                  } j                  }t        | j                        |rt              dz   j                  k\  rO|j                         t        t        |g       j                   j                          j                          n j                  }D ]
  } ||        y j                  |j                  fdt        dt                    D               |j                   fd|D               |j                  d |D               t               _         j                   dd= y)at  Update sorted-key list by adding all values from `iterable`.

        Runtime complexity: `O(k*log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList(key=neg)
        >>> skl.update([3, 1, 2])
        >>> skl
        SortedKeyList([3, 2, 1], key=<built-in function neg>)

        :param iterable: iterable of values to add

        r#   r\   Nc              3   .   K   | ]  }||z      y wr   r-   r^   s     r(   r`   z'SortedKeyList.update.<locals>.<genexpr>e  ra   rb   r   c              3   \   K   | ]#  }t        t        j                  |             % y wr   )r   r   r<  )r_   _listr"   s     r(   r`   z'SortedKeyList.update.<locals>.<genexpr>g  s!     EUT#dii/0Es   ),c              3   &   K   | ]	  }|d      ywrd   r-   re   s     r(   r`   z'SortedKeyList.update.<locals>.<genexpr>h  s     7ggbk7rg   )r5   r=  r6   rh   r<  rO   r2   rP   r   r   ri   rG   r   r4   rj   rk   r7   )	r"   r;   r5   r=  r6   rl   rm   r4   rI   s	   `      @@r(   rn   zSortedKeyList.updateE  s    

dii06{Q$))+f%fb1		*xx! CI

 ?!&q#f+u!=? 	?EfEE777K	KKNr,   c                 v   | j                   }|sy| j                  |      }t        ||      }|t        |      k(  ry| j                  }| j
                  }t        ||   |      }t        |      }t        ||         }		 ||   |   |k7  ry||   |   |k(  ry|dz  }||	k(  r|dz  }||k(  ryt        ||         }	d}>)a  Return true if `value` is an element of the sorted-key list.

        ``skl.__contains__(value)`` <==> ``value in skl``

        Runtime complexity: `O(log(n))`

        >>> from operator import neg
        >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
        >>> 3 in skl
        True

        :param value: search for value in sorted-key list
        :return: true if `value` in sorted-key list

        FTrN   r   r6   r<  r   rO   r5   r=  
r"   rR   r6   r#   rS   r5   r=  rq   len_keyslen_sublists
             r(   rr   zSortedKeyList.__contains__o  s      ii&#&#f+

%*c*u:%*oSz##%c{35(1HCk!q(? !%*o r,   c                    | j                   }|sy| j                  |      }t        ||      }|t        |      k(  ry| j                  }| j
                  }t        ||   |      }t        |      }t        ||         }		 ||   |   |k7  ry||   |   |k(  r| j                  ||       y|dz  }||	k(  r|dz  }||k(  ryt        ||         }	d}P)a  Remove `value` from sorted-key list if it is a member.

        If `value` is not a member, do nothing.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
        >>> skl.discard(1)
        >>> skl.discard(0)
        >>> skl == [5, 4, 3, 2]
        True

        :param value: `value` to discard from sorted-key list

        NrN   r   )r6   r<  r   rO   r5   r=  rt   rM  s
             r(   r!   zSortedKeyList.discard  s    " ii&#&#f+

%*c*u:%*oSz##%c{35(S#&1HCk!q(?!%*o r,   c                 b   | j                   }|st        dj                  |            | j                  |      }t	        ||      }|t        |      k(  rt        dj                  |            | j                  }| j                  }t	        ||   |      }t        |      }t        ||         }		 ||   |   |k7  rt        dj                  |            ||   |   |k(  r| j                  ||       y|dz  }||	k(  r4|dz  }||k(  rt        dj                  |            t        ||         }	d})aS  Remove `value` from sorted-key list; `value` must be a member.

        If `value` is not a member, raise ValueError.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([1, 2, 3, 4, 5], key=neg)
        >>> skl.remove(5)
        >>> skl == [4, 3, 2, 1]
        True
        >>> skl.remove(0)
        Traceback (most recent call last):
          ...
        ValueError: 0 not in list

        :param value: `value` to remove from sorted-key list
        :raises ValueError: if `value` is not in sorted-key list

        rv   NrN   r   )	r6   rw   rx   r<  r   rO   r5   r=  rt   rM  s
             r(   ry   zSortedKeyList.remove  s7   * 077>??ii&#&#f+077>??

%*c*u:%*oSz##% !4!;!;E!BCCc{35(S#&1HCk!q(?$%8%?%?%FGG!%*o r,   c                    | j                   }| j                  }| j                  }| j                  }||   }||   }||= ||= | xj                  dz  c_        t        |      }	|	| j                  dz	  kD  rH|d   ||<   |r=| j                  |z   }
|
dkD  r||
xx   dz  cc<   |
dz
  dz	  }
|
dkD  r|dxx   dz  cc<   yyt        |      dkD  re|s|dz  }|dz
  }||   j                  ||          ||   j                  ||          ||   d   ||<   ||= ||= ||= |dd= | j                  |       y|	r	|d   ||<   y||= ||= ||= |dd= yr{   )
r5   r=  r6   r7   r2   rO   r4   r8   rj   rQ   )r"   rS   rq   r5   r=  r6   r7   keys_pos	lists_poslen_keys_posrZ   r}   s               r(   rt   zSortedKeyList._delete  s    

:3K	SMcN		Q	8}4::?+"2,F3Ks*ai5MQ&M"QY1,E ai q	Q	  Z!^q7D$KuSz*4Ls, ;r?F4Lsc
sq	LL"2,F3Ksc
sq	r,   c                     || j                  |      nd}|| j                  |      nd}| j                  ||||      S )a  Create an iterator of values between `minimum` and `maximum`.

        Both `minimum` and `maximum` default to `None` which is automatically
        inclusive of the beginning and end of the sorted-key list.

        The argument `inclusive` is a pair of booleans that indicates whether
        the minimum and maximum ought to be included in the range,
        respectively. The default is ``(True, True)`` such that the range is
        inclusive of both minimum and maximum.

        When `reverse` is `True` the values are yielded from the iterator in
        reverse order; `reverse` defaults to `False`.

        >>> from operator import neg
        >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
        >>> it = skl.irange(14.5, 11.5)
        >>> list(it)
        [14, 13, 12]

        :param minimum: minimum value to start iterating
        :param maximum: maximum value to stop iterating
        :param inclusive: pair of booleans
        :param bool reverse: yield values in reverse order
        :return: iterator

        N)min_keymax_keyr   r   )r<  _irange_key)r"   r   r   r   r   rW  rX  s          r(   r   zSortedKeyList.irangeB  sP    8 )0(;$))G$(/(;$))G$W   
 	
r,   c                    | j                   }|st        d      S | j                  }|d}d}nn|d   r5t        ||      }|t	        |      k(  rt        d      S t        ||   |      }n4t        ||      }|t	        |      k(  rt        d      S t        ||   |      }|t	        |      dz
  }	t	        ||	         }
n|d   r>t        ||      }	|	t	        |      k(  r|	dz  }	t	        ||	         }
nMt        ||	   |      }
n=t        ||      }	|	t	        |      k(  r|	dz  }	t	        ||	         }
nt        ||	   |      }
| j                  |||	|
|      S )a  Create an iterator of values between `min_key` and `max_key`.

        Both `min_key` and `max_key` default to `None` which is automatically
        inclusive of the beginning and end of the sorted-key list.

        The argument `inclusive` is a pair of booleans that indicates whether
        the minimum and maximum ought to be included in the range,
        respectively. The default is ``(True, True)`` such that the range is
        inclusive of both minimum and maximum.

        When `reverse` is `True` the values are yielded from the iterator in
        reverse order; `reverse` defaults to `False`.

        >>> from operator import neg
        >>> skl = SortedKeyList([11, 12, 13, 14, 15], key=neg)
        >>> it = skl.irange_key(-14, -12)
        >>> list(it)
        [14, 13, 12]

        :param min_key: minimum key to start iterating
        :param max_key: maximum key to stop iterating
        :param inclusive: pair of booleans
        :param bool reverse: yield values in reverse order
        :return: iterator

        r-   r   rN   )r6   r   r=  r   rO   r   r   )r"   rW  rX  r   r   r6   r=  r   r   r   r   s              r(   
irange_keyzSortedKeyList.irange_keyf  sZ   8 8O


 ?GG|%fg6c&k)8O%eGng>&vw7c&k)8O&uW~w?
 ?&kAoG%.)G|&vw7c&k)qLG!%.1G*5>7CG%fg6c&k)qLG!%.1G)%.'BG||GWgwHHr,   c                 B    | j                  | j                  |            S )a  Return an index to insert `value` in the sorted-key list.

        If the `value` is already present, the insertion point will be before
        (to the left of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_left(1)
        4

        :param value: insertion index of value in sorted-key list
        :return: index

        )_bisect_key_leftr<  r   s     r(   r   zSortedKeyList.bisect_left  s    & $$TYYu%566r,   c                 B    | j                  | j                  |            S )a5  Return an index to insert `value` in the sorted-key list.

        Similar to `bisect_left`, but if `value` is already present, the
        insertion point will be after (to the right of) any existing values.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_right(1)
        5

        :param value: insertion index of value in sorted-key list
        :return: index

        )_bisect_key_rightr<  r   s     r(   r   zSortedKeyList.bisect_right  s    & %%dii&677r,   c                     | j                   }|syt        ||      }|t        |      k(  r| j                  S t        | j                  |   |      }| j                  ||      S )a  Return an index to insert `key` in the sorted-key list.

        If the `key` is already present, the insertion point will be before (to
        the left of) any existing keys.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_key_left(-1)
        4

        :param key: insertion index of key in sorted-key list
        :return: index

        r   )r6   r   rO   r2   r=  r   r"   r#   r6   rS   rq   s        r(   bisect_key_leftzSortedKeyList.bisect_key_left  sZ    & &#&#f+99$**S/3/yyc""r,   c                     | j                   }|syt        ||      }|t        |      k(  r| j                  S t        | j                  |   |      }| j                  ||      S )a4  Return an index to insert `key` in the sorted-key list.

        Similar to `bisect_key_left`, but if `key` is already present, the
        insertion point will be after (to the right of) any existing keys.

        Similar to the `bisect` module in the standard library.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedList([5, 4, 3, 2, 1], key=neg)
        >>> skl.bisect_key_right(-1)
        5

        :param key: insertion index of key in sorted-key list
        :return: index

        r   )r6   r   rO   r2   r=  r   ra  s        r(   bisect_key_rightzSortedKeyList.bisect_key_right	  sZ    & 63'#f+994::c?C0yyc""r,   c                    | j                   }|sy| j                  |      }t        ||      }|t        |      k(  ry| j                  }| j
                  }t        ||   |      }d}t        |      }	t        ||         }
	 ||   |   |k7  r|S ||   |   |k(  r|dz  }|dz  }||
k(  r|dz  }||	k(  r|S t        ||         }
d}D)ad  Return number of occurrences of `value` in the sorted-key list.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([4, 4, 4, 4, 3, 3, 3, 2, 2, 1], key=neg)
        >>> skl.count(2)
        2

        :param value: value to count in sorted-key list
        :return: count

        r   rN   rL  )r"   rR   r6   r#   rS   r5   r=  rq   r   rN  rO  s              r(   r   zSortedKeyList.count3	  s     ii&#&#f+

%*c*u:%*oSz##%c{35(
1HCk!q(? L!%*o r,   c                 <    | j                  | | j                        S )zReturn a shallow copy of the sorted-key list.

        Runtime complexity: `O(n)`

        :return: new sorted-key list

        rF  )r   r<  rE   s    r(   r   zSortedKeyList.copya	  s     ~~d		~22r,   c                 p   | j                   }|st        dj                  |            |d}|dk  r||z  }|dk  rd}||}|dk  r||z  }||kD  r|}||k  rt        dj                  |            | j                  }| j	                  |      }t        ||      }|t        |      k(  rt        dj                  |            |dz  }| j                  }| j                  }	t        |	|   |      }
t        |	      }t        |	|         }	 |	|   |
   |k7  rt        dj                  |            ||   |
   |k(  r&| j                  ||
      }||cxk  r|k  r|S  ||kD  rn?|
dz  }
|
|k(  r4|dz  }||k(  rt        dj                  |            t        |	|         }d}
t        dj                  |            )a  Return first index of value in sorted-key list.

        Raise ValueError if `value` is not present.

        Index must be between `start` and `stop` for the `value` to be
        considered present. The default value, None, for `start` and `stop`
        indicate the beginning and end of the sorted-key list.

        Negative indices are supported.

        Runtime complexity: `O(log(n))` -- approximate.

        >>> from operator import neg
        >>> skl = SortedKeyList([5, 4, 3, 2, 1], key=neg)
        >>> skl.index(2)
        3
        >>> skl.index(0)
        Traceback (most recent call last):
          ...
        ValueError: 0 is not in list

        :param value: value in sorted-key list
        :param int start: start index (default None, start of sorted-key list)
        :param int stop: stop index (default None, end of sorted-key list)
        :return: index of value
        :raises ValueError: if value is not present

        r   r   rN   )
r2   rw   rx   r6   r<  r   rO   r5   r=  r   )r"   rR   r   r   r2   r6   r#   rS   r5   r=  rq   rN  rO  r   s                 r(   r   zSortedKeyList.indexn	  s   : yy3::5ABB=E19TME19E<D!8DLD$;D5=3::5ABBii&#&#f+3::5ABB	

%*c*u:%*oSz##% !7!>!>u!EFFc{35(iiS)C'4'J (4Z1HCk!q(?$%;%B%B5%IJJ!%*o " /66u=>>r,   c                     t        t        | j                  g       }|j                  |       | j	                  || j
                        S )a)  Return new sorted-key list containing all values in both sequences.

        ``skl.__add__(other)`` <==> ``skl + other``

        Values in `other` do not need to be in sorted-key order.

        Runtime complexity: `O(n*log(n))`

        >>> from operator import neg
        >>> skl1 = SortedKeyList([5, 4, 3], key=neg)
        >>> skl2 = SortedKeyList([2, 1, 0], key=neg)
        >>> skl1 + skl2
        SortedKeyList([5, 4, 3, 2, 1, 0], key=<built-in function neg>)

        :param other: other iterable
        :return: new sorted-key list

        rF  )r   r   r5   rj   r   r<  r   s      r(   r   zSortedKeyList.__add__	  s9    & dkk2.e~~f$))~44r,   c                 x    t        t        | j                  g       |z  }| j                  || j                        S )a  Return new sorted-key list with `num` shallow copies of values.

        ``skl.__mul__(num)`` <==> ``skl * num``

        Runtime complexity: `O(n*log(n))`

        >>> from operator import neg
        >>> skl = SortedKeyList([3, 2, 1], key=neg)
        >>> skl * 2
        SortedKeyList([3, 3, 2, 2, 1, 1], key=<built-in function neg>)

        :param int num: count of shallow copies
        :return: new sorted-key list

        rF  )r   r   r5   r   r<  r   s      r(   r   zSortedKeyList.__mul__	  s2      dkk2.4~~f$))~44r,   c                 j    t        t        | j                  g       }t        |       || j                  ffS r   )r   r   r5   r  r#   r   s     r(   r	  zSortedKeyList.__reduce__	  s,    dkk2.T
VTXX.//r,   c                 x    t        |       j                  }dj                  |t        |       | j                        S )zReturn string representation of sorted-key list.

        ``skl.__repr__()`` <==> ``repr(skl)``

        :return: string representation

        z{0}({1!r}, key={2!r}))r  r   rx   r   r<  )r"   	type_names     r(   r  zSortedKeyList.__repr__	  s0     J''	&--idTYYOOr,   c                 
   	 | j                   dk\  sJ t        | j                        t        | j                        cxk(  rt        | j                        k(  sJ  J | j
                  t        d | j                  D              k(  sJ | j                  D ],  }t        dt        |            D ]  }||dz
     ||   k  rJ  . t        dt        | j                              D ],  }| j                  |dz
     d   | j                  |   d   k  r,J  t        | j                  | j                        D ]H  \  }}t        |      t        |      k(  sJ t        ||      D ]  \  }}| j                  |      |k(  rJ  J t        t        | j                              D ]&  }| j                  |   | j                  |   d   k(  r&J  | j                   dz  t        fd| j                  D              sJ | j                   dz	  }t        dt        | j                        dz
        D ]  }t        | j                  |         |k\  rJ  | j                  rw| j
                  | j                  d   k(  sJ t        | j                        | j                  t        | j                        z   k(  sJ t        t        | j                              D ];  }| j                  | j                  |z      }|t        | j                  |         k(  r;J  t        | j                        D ]  }|dz  dz   }	|	t        | j                        k\  r| j                  |   dk(  r6J |	dz   t        | j                        k(  r"| j                  |   | j                  |	   k(  rsJ | j                  |	   | j                  |	dz      z   }
|
| j                  |   k(  rJ  yy#  t        j                  t        j                          t#        d| j
                         t#        d	| j                          t#        d
| j                         t#        dt        | j                               t#        d| j                         t#        dt        | j                               t#        d| j                         t#        dt        | j                               t#        d| j                         t#        dt        | j                               t#        d| j                          xY w)zRCheck invariants of sorted-key list.

        Runtime complexity: `O(n)`

        r\   c              3   2   K   | ]  }t        |        y wr   r  re   s     r(   r`   z'SortedKeyList._check.<locals>.<genexpr>
  r  r  rN   rV   r   c              3   :   K   | ]  }t        |      k    y wr   r  r  s     r(   r`   z'SortedKeyList._check.<locals>.<genexpr>(
  r  r  r  rO   rH   r  r   r   r  r  rN  keysr  r  N)r4   rO   r6   r5   r=  r2   r  rk   r   r<  r  r7   r8   r  r   r!  r"  r#  )r"   rf   rS   val_sublistkey_sublistrm   r#   rY   r$  rZ   r%  r  s              @r(   r&  zSortedKeyList._check
  sS   J	::?"?t{{#s4;;'7J3tzz?JJJJJ99#L#L LLLL  :: < CL1 <C"37+ws|;;;<< QDJJ0 Ezz#'*2.$**S/!2DDDDE
 -0TZZ,H 1([;'3{+;;;; #K = 1HC99S>S00011 S-. ?{{3'4::c?2+>>>>?
 ZZ1_FIT[[IIII
 ::?DQDKK 01 45 54;;s+,4445 {{yyDKKN2224;;'4<<#dkk:J+JJJJ !T[[!12 9C;;t||c'9:D3t{{3'7#88889 !. =C AXNEDKK 00#{{3/1444c$++&66#{{3/4;;u3EEEE$(KK$6UQY9O$O	(DKK,<<<<= *	SZZ0%#&$**%(DLL)+s4;;/0'4;;'+s4;;/0'4;;'*c$**o.&$**%+s4;;/0'4;;'sI   B:O
 >AO
 A(O
 7AO
  BO
 C O
 AO
 <O
 6O
 O
 
D=Tr(  r'  ))r   r)  r*  r   r9  r<   r?   r+  r#   rL   rG   r   rQ   rn   r9   rr   r!   ry   rt   r   r[  rY  r   r   r,  rb  r]  rd  
bisect_keyr_  r   r   r-  r   r   r.  r   r	  r.   r  r&  r-   r,   r(   r@   r@     s   0 !%( "#J # #  

 F)X$N%N G.b.b2j9x <H!
H @L QIf K7,8* F#B '#B "J(+\3 HR?j5. H5(0
 	P 	PPr,   r@   )z...)1r   
__future__r   r!  r  r,  r   r   r   	itertoolsr   r   r	   mathr
   operatorr   r   r   r   r   r   r   r   textwrapr   collections.abcr   r   ImportErrorcollections	functoolsr   r   r   r   r   r   threadr   dummy_threadr   _thread_dummy_threadr.   r0   r9  r@   SortedListWithKeyr-   r,   r(   <module>r     s     & 
  4 4 , ,  6 6 6 69  
%%+$ !,%
<~ ~B2
xJ xv " iQ  6556  +*+  ,+,s6   B  ,B3 :C  B0/B03C CCC