कठिन 0 हल किए गए 0% स्वीकृति

Shortest Delivery Tour

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

आप क्या सीखेंगे

  • देखे गए शहरों को बिट के रूप में रखना
  • उपसमुच्चय और आख़िरी शहर पर DP लिखना
  • छोटे TSP को सटीक रूप से हल करना

समस्या

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.

सीमाएँ

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

उदाहरण

उदाहरण 1
इनपुट:
distances = [
    [0, 10, 15, 20],
    [10, 0, 35, 25],
    [15, 35, 0, 30],
    [20, 25, 30, 0]
]

अपेक्षित आउटपुट:
expected = 80
इनपुट:
std::vector<std::vector<long long>> distances = {
    {0, 10, 15, 20},
    {10, 0, 35, 25},
    {15, 35, 0, 30},
    {20, 25, 30, 0}
};

अपेक्षित आउटपुट:
long long expected = 80;
इनपुट:
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}
};

अपेक्षित आउटपुट:
long expected = 80;

व्याख्या

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

उदाहरण 2
इनपुट:
distances = [
    [0]
]

अपेक्षित आउटपुट:
expected = 0
इनपुट:
std::vector<std::vector<long long>> distances = {
    {0}
};

अपेक्षित आउटपुट:
long long expected = 0;
इनपुट:
long[][] distances = new long[][] {
    new long[] {0}
};

अपेक्षित आउटपुट:
long expected = 0;

व्याख्या

With one city there is nowhere to go: 0.

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

क्योंकि cities की संख्या कम है, सीधे सभी tours गिनने के बजाय यह track करें कि कौन-सी cities visit हो चुकी हैं.

संकेत 2

cities के subsets पर dynamic programming करें और हर visited set के साथ हर city पर खत्म होने का best cost याद रखें.

संकेत 3

city 0 से start और उसी पर end करना न भूलें, और उन paths को भी संभालें जो बहुत महंगे हैं लेकिन valid हैं.

अपेक्षित जटिलता

समय O(n^2 2^n), अतिरिक्त स्थान O(n 2^n)

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।