Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Algoritmi greedy
Algoritmi greedy
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussioni

Guida a Algoritmi greedy · 5/6

Practice Problems

Per ora questo capitolo è disponibile solo in inglese.

Most greedy problems fall apart the moment you find the right ordering. The four problems below each exercise a different greedy rule. Before reading a solution, pick your rule and try to justify it in one sentence.

Problem 1. Choosing inspection times

Each sensor in a plant has a time window [l, r] (both ends inclusive) in which its reading must be checked. An inspector does a round at chosen moments and checks every sensor whose window contains that moment. Find the fewest rounds that check every sensor, and their times.

Approach: sort windows by end time. The earliest-ending unchecked window must be inspected by its end anyway, so placing the round as late as possible, at r, covers the most later windows. As an exchange argument: moving the first round of an optimal plan to r never uncovers a window.

def min_check_times(windows):
    times = []
    for l, r in sorted(windows, key=lambda w: w[1]):
        if not times or times[-1] < l:  # last round happened before this window
            times.append(r)
    return times


print(min_check_times([(1, 4), (2, 6), (5, 8), (7, 9), (10, 12)]))  # [4, 8, 12]

Problem 2. Loading spices (fractional knapsack)

A cart carries at most W kg. Each spice has a total value and weight, and you may scoop any portion of it. Find the maximum value you can load.

Approach: load spices in order of value per kilogram. When a spice is heavier than the remaining capacity, take just enough to fill the cart and stop. Swapping some expensive spice for a cheaper one can only lose value, so the rule is optimal. For exact results use fractions.Fraction, or compare ratios by cross-multiplication instead of division.

def max_cart_value(items, capacity):
    """items: list of (value, weight)."""
    total = 0.0
    for value, weight in sorted(items, key=lambda it: it[0] / it[1], reverse=True):
        if capacity <= 0:
            break
        take = min(weight, capacity)
        total += value * take / weight
        capacity -= take
    return total


print(max_cart_value([(120, 3), (100, 5), (60, 4)], 10))  # 250.0

If items cannot be split (0/1 knapsack) this rule is wrong. With (60, 10), (100, 20), (120, 30) and capacity 50, ratio-greedy gets 160 while the optimum is 220.

Problem 3. Tasks finished before their deadlines

Each task has a duration and a deadline, and you process one task at a time without breaks, starting at time 0. Maximize the number of tasks finished on time (late tasks are simply not done).

Approach: accept tasks in order of deadline, and whenever the running time overshoots the current deadline, drop the longest task accepted so far. Dropping the longest keeps the count the same while freeing the most time for later tasks. You need a max-heap, so store negated durations in Python.

Domande su questo capitolo?
Capitolo precedenteComplexityCapitolo successivoReal-World Use
import heapq


def max_on_time(tasks):
    """tasks: list of (duration, deadline)."""
    heap, time = [], 0
    for duration, deadline in sorted(tasks, key=lambda t: t[1]):
        heapq.heappush(heap, -duration)
        time += duration
        if time > deadline:
            time += heapq.heappop(heap)  # negative, so this subtracts the longest duration
    return len(heap)


print(max_on_time([(3, 4), (2, 5), (4, 7), (1, 8), (3, 9)]))  # 4

Problem 4. Cheapest way to merge files

You want to merge n files of different sizes into one. Merging two files costs the sum of their sizes. Find the minimum total cost.

Approach: each file's size is paid once for every merge it takes part in (its depth in the merge tree), so this is exactly Huffman coding. Always merge the two smallest files.

import heapq


def min_merge_cost(sizes):
    heap = list(sizes)
    heapq.heapify(heap)
    cost = 0
    while len(heap) > 1:
        a = heapq.heappop(heap)
        b = heapq.heappop(heap)
        cost += a + b
        heapq.heappush(heap, a + b)
    return cost


print(min_merge_cost([4, 3, 2, 6]))  # 29

Merging left to right (4+3, 7+2, 9+6) costs 7 + 9 + 15 = 31, while greedy does 2+3, 4+5, 6+9 for 5 + 9 + 15 = 29.

Check yourself

  • Write a small randomized test that compares each solution against brute force. Inputs of size 6 to 8 finish instantly.
  • In problem 1, how does the comparison change if the windows are half-open?
  • In problem 3, does dropping the task you just added (instead of the longest) admit a counterexample?

Summary

  • Inspection times: sort by end, place a point at the end of each uncovered window.
  • Fractional knapsack: sort by value per weight, split only the last item.
  • Deadlines: add by deadline, and on overflow drop the longest task from a heap.
  • File merging: like Huffman, keep merging the two smallest.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.