Tutte le sfide
Difficile 2 risolte 100.0% di accettazione

Shortest Delivery Tour

Visit every city once and return home as cheaply as possible.

Cosa imparerai

  • Store visited cities as bits
  • Write a DP over subsets and last city
  • Solve small TSP instances exactly

Problema

Mostra traduzione

A courier starts at city 0, visits every other city exactly once and returns to city 0. distances[i][j] is the cost from i to j. With at most 15 cities, a bitmask dynamic program (Held–Karp) over visited sets is fast enough.

Implement shortest_tour(distances).

Input

distances: An n × n matrix of travel costs; distances[i][i] = 0.

Output

Return the cost of the cheapest round trip.

Vincoli

1 ≤ n ≤ 15; 0 ≤ cost ≤ 1,000,000

Esempi

Esempio 1
Input:
distances = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0]
]

Output atteso:
expected = 80
Input:
std::vector<std::vector<long long>> distances = {
    {0, 10, 15, 20},
    {10, 0, 35, 25},
    {15, 35, 0, 30},
    {20, 25, 30, 0}
};

Output atteso:
long long expected = 80;
Input:
long[][] distances = new long[][] {
    new long[] {0, 10, 15, 20},
    new long[] {10, 0, 35, 25},
    new long[] {15, 35, 0, 30},
    new long[] {20, 25, 30, 0}
};

Output atteso:
long expected = 80;

Spiegazione

0→1→3→2→0 costs 10 + 25 + 30 + 15 = 80, the cheapest tour.

Esempio 2
Input:
distances = [
    [0]
]

Output atteso:
expected = 0
Input:
std::vector<std::vector<long long>> distances = {
    {0}
};

Output atteso:
long long expected = 0;
Input:
long[][] distances = new long[][] {
    new long[] {0}
};

Output atteso:
long expected = 0;

Spiegazione

With one city there is nowhere to go: 0.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Since the city count is small, try tracking which cities have been visited instead of enumerating all tours directly.

Suggerimento 2

Use dynamic programming over subsets of cities and remember the best cost to end at each city with that visited set.

Suggerimento 3

Be careful to start and end at city 0, and to handle the cases where some paths are extremely expensive but still valid.

Complessità attesa

O(n^2 2^n) time, O(n 2^n) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 837 ms - 5/5 Vedi il codice
2 MPMarinos Papadimitriu C++ 3,483 ms - 3/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 2 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.