챌린지 목록으로 돌아가기
어려움 0명 해결 정답률 0%

Minimum Network Connection Cost

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

배우게 될 내용

  • 크루스칼 알고리즘으로 그래프를 싸게 연결하기
  • 서로소 집합으로 사이클 감지하기
  • 연결할 수 없는 경우 알리기

문제

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

사이클을 만들지 않는 가장 싼 링크를 그리디하게 추가하거나, union-find로 컴포넌트를 확장하세요.

힌트 3

정점을 잇는 usable link가 vertices - 1개보다 적으면 불가능합니다.

예상 복잡도

시간 O(links log links), 추가 공간 O(vertices + links)

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.