ยาก 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

เพราะจำนวนเมืองไม่มาก ลองติดตามว่าไปเยือนเมืองไหนแล้วบ้าง แทนการไล่ดูทุกทัวร์โดยตรง

คำใบ้ 2

ใช้ dynamic programming บนเซตย่อยของเมือง และจำต้นทุนที่ดีที่สุดในการจบที่แต่ละเมืองเมื่อมีเซตที่เยือนแล้วนั้น

คำใบ้ 3

ระวังต้องเริ่มและจบที่เมือง 0 และต้องรองรับกรณีที่บางเส้นทางแพงมากแต่ยังใช้ได้

ความซับซ้อนที่คาดหวัง

เวลา O(n^2 2^n), หน่วยความจำเพิ่ม O(n 2^n)

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก