Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Algoritmos voraces
Algoritmos voraces
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Debates

Guía de Algoritmos voraces · 2/6

How It Works

Por ahora, este capítulo solo está disponible en inglés.

Most greedy algorithms share the same skeleton. Put the candidates in sorted order or into a priority queue, take them out one at a time, and accept each one that does not conflict with the choices made so far. This chapter traces interval scheduling, Huffman coding and meeting-room allocation on small examples.

Interval scheduling (activity selection)

One meeting room has received several requests, and you want to fit in as many meetings as possible without overlaps. Each meeting is a half-open interval [start, end), so a meeting ending at 4 lets the next one start at 4. The greedy rule is "take the meeting that ends first".

def trace(intervals):
    last_end = float("-inf")
    for start, end in sorted(intervals, key=lambda iv: iv[1]):
        ok = start >= last_end
        print(f"({start}, {end}) last_end={last_end} -> {'take' if ok else 'skip'}")
        if ok:
            last_end = end


trace([(1, 3), (2, 5), (4, 7), (1, 8), (6, 9), (8, 10)])

After sorting by end time, the scan goes like this.

StepMeetingPrevious endDecisionNew end
1(1, 3)nonetake3
2(2, 5)3starts before 3, skip3
3(4, 7)3take7
4(1, 8)7skip7
5(6, 9)7skip7
6(8, 10)7take10

The result is (1, 3), (4, 7), (8, 10): three meetings, and no schedule can hold more.

Why other rules fail

Rules that sound reasonable collapse under a single counterexample.

RuleCounterexampleGreedyOptimal
Earliest start(0, 10), (1, 2), (3, 4)12
Shortest meeting(1, 5), (4, 7), (6, 10)12
Fewest conflictslarger counterexamples are knownfewer than optimal-

Taking the meeting that ends first leaves the most time for everything else. By induction, the k-th meeting chosen by greedy ends no later than the k-th meeting of any other valid schedule; that is the "greedy stays ahead" argument.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorGreedy ConceptsCapítulo siguienteImplementation

Huffman coding

Huffman coding builds a prefix code that gives short bit strings to frequent symbols and long ones to rare symbols, minimizing the total length. The greedy rule is "merge the two lightest groups". Let's follow the frequencies a=5, b=9, c=12, d=13, e=16, f=45.

import heapq

freq = {"a": 5, "b": 9, "c": 12, "d": 13, "e": 16, "f": 45}
heap = [(w, ch) for ch, w in freq.items()]
heapq.heapify(heap)
total = 0
while len(heap) > 1:
    w1, x = heapq.heappop(heap)
    w2, y = heapq.heappop(heap)
    total += w1 + w2
    print(f"{x}({w1}) + {y}({w2}) = {w1 + w2}")
    heapq.heappush(heap, (w1 + w2, x + y))
print("total bits:", total)  # 224
StepTwo lightestMerged weightRunning cost
1a(5), b(9)1414
2c(12), d(13)2539
3ab(14), e(16)3069
4cd(25), abe(30)55124
5f(45), cdabe(55)100224

In the finished tree f sits at depth 1, c, d and e at depth 3, and a and b at depth 4. Each symbol's code length equals its depth, and the sum of frequency times length is 45 + 36 + 39 + 48 + 20 + 36 = 224 bits, the same as the sum of all merged weights (14 + 25 + 30 + 55 + 100). A fixed 3-bit code would need 300 bits, so Huffman saves about 25%.

An exchange argument shows that some optimal tree places the two lightest symbols as siblings at the deepest level: if a heavier symbol were deeper, swapping the two could not increase the cost.

Meeting rooms (minimum platforms)

Now every meeting must take place, and you want the minimum number of rooms. Counting the platforms a railway station needs is the same problem. Scan meetings by start time and keep the end times of rooms in use in a min-heap. If the room that frees up first is free by the time the meeting starts, reuse it; otherwise open a new room.

import heapq


def min_rooms(meetings):
    ends = []  # end times of rooms in use (min-heap)
    for start, end in sorted(meetings):
        if ends and ends[0] <= start:
            heapq.heapreplace(ends, end)  # reuse the room that frees up first
        else:
            heapq.heappush(ends, end)     # open a new room
    return len(ends)


print(min_rooms([(9, 10), (9, 12), (10, 11), (11, 13), (12, 13)]))  # 2
MeetingHeap beforeActionHeap after
(9, 10)emptynew room[10]
(9, 12)[10]10 is after 9, new room[10, 12]
(10, 11)[10, 12]reuse the room free at 10[11, 12]
(11, 13)[11, 12]reuse the room free at 11[12, 13]
(12, 13)[12, 13]reuse the room free at 12[13, 13]

If, as with train platforms, an arrival and a departure at the same minute cannot share a platform, change ends[0] <= start to ends[0] < start. Whether interval endpoints are inclusive is the most common source of greedy bugs.

Summary

  • The greedy skeleton is: sort or heapify by a rule, take items one by one, accept those that do not conflict.
  • Interval scheduling takes the earliest end, Huffman merges the two lightest groups, room allocation reuses the room that frees up first.
  • Plausible alternative rules break on tiny counterexamples, so always be able to say why your rule is right.
  • Decide inclusive versus exclusive endpoints (< versus <=) from the problem statement.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.