a �DOg]Y�@s@dZgd�Zdd�Zdd�Zdd�Zdd �Zd d �Zd d �Zdd�Zdd�Z dd�Z dd�Z dd�Z dd�Z ddd�dd�Zd)dd �Zd*d!d"�Zz d#d$lTWney�Yn0zd#d%lmZWney�Yn0zd#d&lm Z Wney�Yn0zd#d'lmZWne�yYn0ed(k�r|dd?}||}||kr>|||<|}qq>q|||<dS�Nr r�r�startpos�pos�newitem� parentpos�parentrrrr �s r cCs�t|�}|}||}d|d}||krj|d}||krL||||ksL|}||||<|}d|d}q |||<t|||�dS�Nrr )r r �rr)�endposr(r*�childpos�rightposrrrrs  rcCsJ||}||kr>|dd?}||}||kr>|||<|}qq>q|||<dSr&rr'rrr� _siftdown_maxs r2cCs�t|�}|}||}d|d}||krj|d}||krL||||ksL|}||||<|}d|d}q |||<t|||�dSr-)r r2r.rrrr"%s  r"NF��key�reversec gsg}|j}|r t}t}t}d}nt}t}t}d}|du�rttt |��D]:\} } z| j } || �| || g�WqHt y�YqH0qH||�t |�dkr�z2|d\} } } } | V| �| d<||| �q�Wq�t y�||�Yq�0q�|�r|d\} } } | V| j EdHdSttt |��D]H\} } z(| j } | �} ||| �| || | g�Wnt �ydYn0�q ||�t |�dk�r�zF|d\}} } } } | V| �} || �| d<| | d<||| ��q�Wnt �y�||�Yn0�qr|�r|d\}} } } | V| j EdHdS)N�����r r r)r r%r#r$rrr� enumerate�map�iter�__next__� StopIterationr �__self__)r4r5� iterables�h�h_append�_heapify�_heappop� _heapreplace� direction�order�it�next�value�s� key_valuerrrr:sl        rc s�|dkr6t|�}t�}t||�d�}||ur0gS|gSz t|�}WnttfyXYn0||krvt|�d�d|�S�du�rt|�}dd�tt|�|�D�}|s�|St |�|dd}|}t } |D].} | |kr�| || |f�|d\}} |d7}q�|� �dd�|D�St|�}�fdd�tt|�|�D�}|�s<|St |�|dd}|}t } |D]>} �| �} | |k�r\| || || f�|d\}} } |d7}�q\|� �d d�|D�S) Nr ��defaultr4�r4cSsg|]\}}||f�qSrr��.0r!�elemrrr� ��znsmallest..r cSsg|] \}}|�qSrr�rNrOrDrrrrP�rQcsg|]\}}�|�||f�qSrrrMrLrrrP�rQcSsg|]\}}}|�qSrr�rN�krDrOrrrrPrQ) r9�object�minr � TypeError�AttributeError�sorted�ziprr%r$�sort�r �iterabler4rE�sentinel�result�size�toprDrBrO�_orderrT�_elemrrLrr�sV        rc s�|dkr6t|�}t�}t||�d�}||ur0gS|gSz t|�}WnttfyXYn 0||krxt|�dd�d|�S�du�rt|�}dd�ttd| d�|�D�}|s�|St |�|dd}| }t } |D].} || kr�| || |f�|d\}} |d8}q�|j dd �d d�|D�St|�}�fd d�ttd| d�|�D�}|�sP|St |�|dd}| }t } |D]>} �| �} || k�rr| || || f�|d\}} } |d8}�qr|j dd �d d�|D�S) Nr rJTr3cSsg|]\}}||f�qSrrrMrrrrP"rQznlargest..r r6)r5cSsg|] \}}|�qSrrrRrrrrP/rQcsg|]\}}�|�||f�qSrrrMrLrrrP3rQcSsg|]\}}}|�qSrrrSrrrrPArQ) r9rU�maxr rWrXrYrZrrrr[r\rrLrr sV      "    rr )�*)r$)r%)r#�__main__)N)N)� __about__�__all__rrrrrr#r$r%r rr2r"rrr�_heapq� ImportError�__name__�doctest�print�testmodrrrr�!sH^    5 < ;