Quay lại danh sách thử thách
Khó 0 đã giải Tỷ lệ chấp nhận 0%

Minimum Network Connection Cost

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

Bạn sẽ học được gì

  • Nối đồ thị với chi phí thấp bằng thuật toán Kruskal
  • Phát hiện chu trình bằng tập rời nhau
  • Báo khi đồ thị không thể liên thông

Đề bài

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.

Ràng buộc

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.

Ví dụ

Ví dụ 1
Đầu vào:
links = [
    [1, 2, 4],
    [2, 3, 2],
    [1, 3, 7]
]
vertices = 3

Kết quả mong đợi:
expected = 6
Đầu vào:
std::vector<std::vector<long long>> links = {
    {1, 2, 4},
    {2, 3, 2},
    {1, 3, 7}
};
long long vertices = 3;

Kết quả mong đợi:
long long expected = 6;
Đầu vào:
long[][] links = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 2},
    new long[] {1, 3, 7}
};
long vertices = 3;

Kết quả mong đợi:
long expected = 6;

Giải thích

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

Ví dụ 2
Đầu vào:
links = [
    [1, 2, 4]
]
vertices = 3

Kết quả mong đợi:
expected = -1
Đầu vào:
std::vector<std::vector<long long>> links = {
    {1, 2, 4}
};
long long vertices = 3;

Kết quả mong đợi:
long long expected = -1;
Đầu vào:
long[][] links = new long[][] {
    new long[] {1, 2, 4}
};
long vertices = 3;

Kết quả mong đợi:
long expected = -1;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Bạn cần một tập cạnh rẻ nhất nhưng vẫn nối được toàn bộ đỉnh, nên đây là bài spanning tree.

Gợi ý 2

Tham lam thêm cạnh rẻ nhất không tạo chu trình, hoặc phát triển các thành phần với union-find.

Gợi ý 3

Nếu số cạnh hữu ích ít hơn vertices - 1 thì không thể nối hết đồ thị.

Độ phức tạp mong đợi

thời gian O(links log links), bộ nhớ phụ O(vertices + links)

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.