Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionTASTEWINMGestion de fichiersOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailInvestissementTASTESTOCKApplication de bureau de trading automatique d'actionsCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécuritéTASTEWINMUn gestionnaire de fichiers à deux volets, pensé pour le clavier

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Investissement

TASTESTOCKDu trading automatique d'actions selon vos règles : quand, et quoi

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesÀ proposPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
Hier
Vues au total
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation Union-Find
Union-Find
Concepts: Disjoint Sets and Union-FindHow It Works: Tracing find and unionImplementation: Building a DSU ClassComplexity: Inverse Ackermann in Plain WordsPractice ProblemsReal-World Use and Pitfalls
Discussions

Guide Union-Find · 4/6

Complexity: Inverse Ackermann in Plain Words

Ce chapitre n'est disponible qu'en anglais pour le moment.

Union-find is often described as running in "nearly constant time". This chapter explains what that phrase really means, how the cost drops as each optimization is added, and how union-find compares with the alternatives.

Cost by optimization

Here n is the number of elements and m the number of find and union calls. union calls find twice internally, so it costs the same order as find.

ImplementationOne find (worst case)m operations in total
Quick-find (label array)O(1), but union is O(n)O(m n)
Plain trees (no optimization)O(n)O(m n)
Union by size or rank onlyO(log n)O(m log n)
Path compression onlyO(n), amortized O(log n)O(m log n)
BothO(log n)O(m α(n))

The α(n) in the last row is the inverse Ackermann function.

What is the inverse Ackermann function?

The Ackermann function grows unimaginably fast: nudge its input up a little and the output explodes. The inverse Ackermann function α(n) asks the opposite question: how large must the input be before the Ackermann function reaches n? Because the Ackermann function grows absurdly fast, α(n) grows absurdly slowly.

In plain words: even if you had far more elements than there are atoms in the observable universe, α(n) would still be at most 4. So the total cost O(m α(n)) can be read in practice as "a small constant per operation". Strictly speaking it is not a constant, and Tarjan showed that this bound cannot be beaten by any pointer-based structure of this kind.

Placing it next to the logarithm makes the difference obvious.

nlog2 nα(n)
164at most 3
65,53616at most 4
10^80 (roughly the atoms in the observable universe)about 266at most 4

What amortized means

With path compression, an individual find can still take a long time. But that find flattens the path it walked, so the calls that follow become cheaper. The cost is therefore measured as a total over all m operations rather than per call; this is amortized analysis. If the worst case of a single call matters, as in hard real-time systems, keep this in mind.

Seeing it for yourself

Des questions sur ce chapitre ?
Chapitre précédentImplementation: Building a DSU ClassChapitre suivantPractice Problems

The code below compares the deepest node in a tree built without optimizations against one built with both optimizations.

def depth(parent, x):
    d = 0
    while parent[x] != x:
        x = parent[x]
        d += 1
    return d

n = 1 << 12
naive = list(range(n))
for i in range(1, n):
    naive[i - 1] = i            # hang the previous root under the next element
print(max(depth(naive, x) for x in range(n)))   # 4095

parent, size = list(range(n)), [1] * n
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
for i in range(1, n):
    ra, rb = find(i - 1), find(i)
    if size[ra] < size[rb]:
        ra, rb = rb, ra
    parent[rb] = ra
    size[ra] += size[rb]
print(max(depth(parent, x) for x in range(n)))  # 1

With union by size, each new singleton is hung directly under the root of the big tree, so the maximum depth stays at 1.

Timing operations

Run 200,000 random unions while growing the number of elements a thousandfold. The time per operation stays in the low microseconds and does not grow in proportion to n. Depending on your machine it may creep up a little, mostly because larger arrays fit less well in the CPU cache, not because the algorithm does more work.

import random
import time

def ns_per_op(n, m=200_000):
    parent, size = list(range(n)), [1] * n
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    start = time.perf_counter()
    for _ in range(m):
        ra, rb = find(random.randrange(n)), find(random.randrange(n))
        if ra != rb:
            if size[ra] < size[rb]:
                ra, rb = rb, ra
            parent[rb] = ra
            size[ra] += size[rb]
    return (time.perf_counter() - start) / m * 1e9

for n in (10**3, 10**5, 10**6):
    print(n, f"{ns_per_op(n):.0f} ns/op")

Space complexity

Two arrays, parent and size (or rank), give O(n) space. Ranks never exceed log n, so a very small integer type is enough for them. A recursive find can push as many stack frames as the tree is tall in the worst case, so in languages with a low recursion limit, such as Python, the iterative version is the safe choice.

import sys
# If you must use a recursive find, you may need a higher limit
sys.setrecursionlimit(1 << 20)

def find_rec(parent, x):
    if parent[x] != x:
        parent[x] = find_rec(parent, parent[x])
    return parent[x]

Comparison with alternatives

ApproachAdd edgeConnectivity queryDelete edgeNotes
Union-findnearly O(1)nearly O(1)not supportedmerges only
BFS/DFS per queryO(1)O(V + E)O(1)simple when queries are rare
Precomputed componentsfull recomputeO(1)full recomputefor graphs that never change
Dynamic connectivity structuresO(log^2 n) amortizedO(log n)supportedcomplex to implement

Summary

With both optimizations, union-find runs m operations in O(m α(n)) time and O(n) space. Since α(n) is at most 4 for any realistic input, you can treat it as a constant. When edges are never deleted and queries are frequent, it is far more efficient than rerunning BFS or DFS.

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.