ยาก 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Minimum Network Connection Cost

Choose undirected links so that every vertex can reach every other vertex, with minimum total cost.

สิ่งที่คุณจะได้เรียนรู้

  • เชื่อมกราฟด้วยต้นทุนต่ำด้วยอัลกอริทึมของ Kruskal
  • ตรวจหาวงจรด้วยเซตไม่มีส่วนร่วม
  • แจ้งเมื่อกราฟเชื่อมกันไม่ได้

โจทย์

Choose undirected links so that every vertex can reach every other vertex, with minimum total cost. A link can be used in either direction. Return −1 if the available links cannot connect the whole network. You do not need to return the selected links.

Implement minimum_network_connection_cost(vertices, links).

Input

vertices: The number of network vertices.

links: Available links [u, v, cost].

Output

Return the minimum total cost, −1 if impossible, or 0 for a one-vertex network.

เงื่อนไข

1 ≤ vertices ≤ 100,000. 0…200,000 links; endpoints are distinct vertices in 1…vertices. Costs are 1…1,000,000,000. Parallel links are allowed. The total fits signed 64-bit.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
links = [
    [1, 2, 4],
    [2, 3, 2],
    [1, 3, 7]
]
vertices = 3

ผลลัพธ์ที่คาดหวัง:
expected = 6
อินพุต:
std::vector<std::vector<long long>> links = {
    {1, 2, 4},
    {2, 3, 2},
    {1, 3, 7}
};
long long vertices = 3;

ผลลัพธ์ที่คาดหวัง:
long long expected = 6;
อินพุต:
long[][] links = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 2},
    new long[] {1, 3, 7}
};
long vertices = 3;

ผลลัพธ์ที่คาดหวัง:
long expected = 6;

คำอธิบาย

Choose links costing 4 and 2 to connect all three vertices. Their total is 6; the cost-7 link is unnecessary.

ตัวอย่างที่ 2
อินพุต:
links = [
    [1, 2, 4]
]
vertices = 3

ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::vector<std::vector<long long>> links = {
    {1, 2, 4}
};
long long vertices = 3;

ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
long[][] links = new long[][] {
    new long[] {1, 2, 4}
};
long vertices = 3;

ผลลัพธ์ที่คาดหวัง:
long expected = -1;

คำอธิบาย

Vertex 3 has no connection. No selection can connect the entire network.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

ต้องการชุดเส้นเชื่อมที่ถูกที่สุดแต่ยังทำให้ทุกจุดยอดเชื่อมถึงกันได้ จึงเป็นแนว spanning tree

คำใบ้ 2

เพิ่มเส้นเชื่อมที่ถูกที่สุดซึ่งไม่สร้าง cycle หรือใช้ union-find เพื่อขยาย component

คำใบ้ 3

ถ้าเส้นเชื่อมที่ใช้ได้มีน้อยกว่าจำนวน vertices ลบหนึ่ง คำตอบเป็นไปไม่ได้

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

เวลา O(links log links), หน่วยความจำเพิ่ม O(vertices + links)

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

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

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

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

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