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 Plus courts chemins et arbres couvrants
Plus courts chemins et arbres couvrants
ConceptsHow it worksImplementationComplexityPractice problemsReal-world use
Discussions

Guide Plus courts chemins et arbres couvrants · 3/6

Implementation

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

This chapter builds Dijkstra with a binary heap and Kruskal with union-find in Python, then shows the same Dijkstra routine in C++, Java and TypeScript. Vertices are numbered 0..n-1 and the graph is an adjacency list adj[u] = [(v, w), ...].

Dijkstra in Python

import heapq
from math import inf

def dijkstra(adj, source):
    n = len(adj)
    dist = [inf] * n
    parent = [-1] * n
    dist[source] = 0
    heap = [(0, source)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:  # stale entry, u already has a better distance
            continue
        for v, w in adj[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                parent[v] = u
                heapq.heappush(heap, (nd, v))
    return dist, parent

def path_to(parent, target):
    path = []
    while target != -1:
        path.append(target)
        target = parent[target]
    return path[::-1]

adj = [[(1, 4), (2, 1)], [(3, 1)], [(1, 2), (3, 5)], [(4, 3)], []]
dist, parent = dijkstra(adj, 0)
print(dist)  # [0, 3, 1, 4, 7]
print(path_to(parent, 4))  # [0, 2, 1, 3, 4]

Line by line:

  • heapq turns a plain list into a binary min-heap; tuples compare by their first item, so the smallest distance comes out first.
  • dist starts at infinity, parent at -1 (no predecessor yet).
  • if d > dist[u]: continue is the lazy-deletion check. Without it every stale pair would rescan u's edges and the running time would grow.
  • On an improvement we update dist[v] and parent[v] and push a new pair; the old pair stays in the heap and will be skipped.
  • path_to walks the parent links back to the source. Check dist[target] != inf first; for an unreachable target it would return just [target].

To answer a single-pair query, return as soon as the target is popped: its distance is final at that moment.

Kruskal with union-find in Python

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b:
            return False  # would close a cycle
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a  # union by size
        self.size[a] += self.size[b]
        return True

def kruskal(n, edges):
    dsu = DSU(n)
    total, chosen = 0, []
    for w, u, v in sorted(edges):
        if dsu.union(u, v):
            total += w
            chosen.append((u, v, w))
            if len(chosen) == n - 1:
                break
    return total, chosen

edges = [(1, 0, 1), (2, 1, 2), (3, 0, 2), (4, 2, 3), (5, 1, 3)]  # (w, u, v)
print(kruskal(4, edges))  # (7, [(0, 1, 1), (1, 2, 2), (2, 3, 4)])
Des questions sur ce chapitre ?
Chapitre précédentHow it worksChapitre suivantComplexity

Edges are stored as (w, u, v) so sorted orders them by weight. union returns False when both ends are already in the same component, which is exactly the "would form a cycle" test. If fewer than n - 1 edges are chosen, the graph is disconnected and the result is a minimum spanning forest.

The same Dijkstra in C++

std::priority_queue is a max-heap by default; greater turns it into a min-heap. Use long long so sums do not overflow.

#include <functional>
#include <limits>
#include <queue>
#include <vector>
using namespace std;
using ll = long long;
using State = pair<ll, int>;

vector<ll> dijkstra(const vector<vector<pair<int, ll>>>& adj, int src) {
    vector<ll> dist(adj.size(), numeric_limits<ll>::max());
    priority_queue<State, vector<State>, greater<State>> pq;
    dist[src] = 0;
    pq.push({0, src});
    while (!pq.empty()) {
        auto [d, u] = pq.top();
        pq.pop();
        if (d > dist[u]) continue;
        for (auto [v, w] : adj[u]) {
            if (d + w < dist[v]) {
                dist[v] = d + w;
                pq.push({dist[v], v});
            }
        }
    }
    return dist;
}
// dijkstra(adj, 0) on the example graph returns {0, 3, 1, 4, 7}

The same Dijkstra in Java

PriorityQueue is a min-heap ordered by the comparator. Here each entry is a long[] {distance, vertex}.

import java.util.*;

public class Dijkstra {
    static long[] dijkstra(List<List<int[]>> adj, int src) {
        long[] dist = new long[adj.size()];
        Arrays.fill(dist, Long.MAX_VALUE);
        dist[src] = 0;
        PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));
        pq.add(new long[] {0, src});
        while (!pq.isEmpty()) {
            long[] top = pq.poll();
            long d = top[0];
            int u = (int) top[1];
            if (d > dist[u]) continue;
            for (int[] e : adj.get(u)) {
                int v = e[0];
                if (d + e[1] < dist[v]) {
                    dist[v] = d + e[1];
                    pq.add(new long[] {dist[v], v});
                }
            }
        }
        return dist;
    }
    // dijkstra(adj, 0) on the example graph returns [0, 3, 1, 4, 7]
}

The same Dijkstra in TypeScript

JavaScript has no built-in priority queue, so we write a small binary heap: push sifts the new item up, pop moves the last item to the root and sifts it down.

type Item = [dist: number, vertex: number];

class MinHeap {
  private a: Item[] = [];
  get size() { return this.a.length; }
  push(item: Item) {
    const a = this.a;
    a.push(item);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p][0] <= a[i][0]) break;
      [a[p], a[i]] = [a[i], a[p]];
      i = p;
    }
  }
  pop(): Item {
    const a = this.a;
    const top = a[0];
    const last = a.pop()!;
    if (a.length > 0) {
      a[0] = last;
      for (let i = 0; ; ) {
        const l = 2 * i + 1, r = l + 1;
        let m = i;
        if (l < a.length && a[l][0] < a[m][0]) m = l;
        if (r < a.length && a[r][0] < a[m][0]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]];
        i = m;
      }
    }
    return top;
  }
}

function dijkstra(adj: [number, number][][], src: number): number[] {
  const dist = new Array<number>(adj.length).fill(Infinity);
  const heap = new MinHeap();
  dist[src] = 0;
  heap.push([0, src]);
  while (heap.size > 0) {
    const [d, u] = heap.pop();
    if (d > dist[u]) continue;
    for (const [v, w] of adj[u]) {
      if (d + w < dist[v]) {
        dist[v] = d + w;
        heap.push([dist[v], v]);
      }
    }
  }
  return dist;
}

console.log(dijkstra([[[1, 4], [2, 1]], [[3, 1]], [[1, 2], [3, 5]], [[4, 3]], []], 0)); // [ 0, 3, 1, 4, 7 ]

Summary

  • Dijkstra is a heap loop: pop, skip if stale, relax outgoing edges, push improvements.
  • Keep a parent array if you need the path, not just the distance.
  • Kruskal is "sort edges, union if not already connected"; union-find makes the cycle test nearly constant time.
  • The C++, Java and TypeScript versions mirror the Python one line for line; only the heap API differs.

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.