K i (dZddlmZGddZy)z Union-find data structure. )groupsc0eZdZdZddZdZdZdZdZy) UnionFindaUnion-find data structure. Each unionFind instance X maintains a family of disjoint sets of hashable objects, supporting the following two methods: - X[item] returns a name for the set containing the given item. Each set is named by an arbitrarily-chosen one of its members; as long as the set remains unchanged it will keep the same name. If the item is not yet part of a set in X, a new singleton set is created for it. - X.union(item1, item2, ...) merges the sets containing each item into a single larger set. If any item is not yet part of a set in X, it is added to X as one of the members of the merged set. Union-find data structure. Based on Josiah Carlson's code, https://code.activestate.com/recipes/215912/ with significant additional changes by D. Eppstein. http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py Ncr|d}i|_i|_|D] }d|j|<||j|<"y)zCreate a new empty union-find structure. If *elements* is an iterable, this structure will be initialized with the discrete partition on the given set of elements. N)parentsweights)selfelementsxs _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/networkx/utils/union_find.py__init__zUnionFind.__init__sF  H   ADLLODLLO c ||jvr ||j|<d|j|<|Sg}|j|}||k7r(|j||}|j|}||k7r(|D]}||j|<|S)z:Find and return the name of the set containing the object.r)r r append)r objectpathrootancestors r __getitem__zUnionFind.__getitem__.s  %#)DLL #$DLL M||F#fn KK F<<'Dfn  *H%)DLL " * rc,t|jS)zBIterate through all items ever found or unioned by this structure.)iterr )r s r__iter__zUnionFind.__iter__DsDLL!!rc#K|jD]}||} t|jjEd{y7w)a]Iterates over the sets stored in this structure. For example:: >>> partition = UnionFind("xyz") >>> sorted(map(sorted, partition.to_sets())) [['x'], ['y'], ['z']] >>> partition.union("x", "y") >>> sorted(map(sorted, partition.to_sets())) [['x', 'y'], ['z']] N)r rvalues)r r _s rto_setszUnionFind.to_setsHsA AQA $,,'..000s=AAAc tt|Dchc]}| c}fdd} t|}|D]5}j|xxj|z cc<|j |<7ycc}w#t$rYywxYw)z8Find the sets containing the objects and merge them all.c"j|SN)r )rr s rz!UnionFind.union..`s$,,q/rT)keyreverseN)rsortednext StopIterationr r )r objectsr rootsrr"s` runionzUnionFind.union[s ")*Qa*0ISW    ;D #A LL $,,q/ 1 "DLLO #+    s A4 A99 BBr!) __name__ __module__ __qualname____doc__rrrrr+rrrrrs ,  ,"1&#rrN)r/networkx.utilsrrrrrr1s"b#b#r