チャレンジ一覧に戻る
難しい 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 つずつ開いてみましょう。

ヒント 1

全頂点をつなぎつつ最小コストにするには、最小全域木を考えます。

ヒント 2

サイクルを作らない最安のリンクを順に足すか、union-findで成分を広げます。

ヒント 3

使えるリンクが頂点数-1本未満なら、グラフ全体はつながらず不可能です。

目安の計算量

時間 O(links log links)、追加メモリ O(vertices + links)

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。