Zurück zu den Herausforderungen
Schwierig 0 gelöst 0% Erfolgsquote

Minimum Network Connection Cost

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

Das lernst du

  • Einen Graphen günstig mit dem Kruskal-Algorithmus verbinden
  • Zyklen mit einer Union-Find-Struktur erkennen
  • Melden, wenn ein Graph nicht verbunden werden kann

Problem

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.

Einschränkungen

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.

Beispiele

Beispiel 1
Eingabe:
links = [
    [1, 2, 4],
    [2, 3, 2],
    [1, 3, 7]
]
vertices = 3

Erwartete Ausgabe:
expected = 6
Eingabe:
std::vector<std::vector<long long>> links = {
    {1, 2, 4},
    {2, 3, 2},
    {1, 3, 7}
};
long long vertices = 3;

Erwartete Ausgabe:
long long expected = 6;
Eingabe:
long[][] links = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 2},
    new long[] {1, 3, 7}
};
long vertices = 3;

Erwartete Ausgabe:
long expected = 6;

Erläuterung

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

Beispiel 2
Eingabe:
links = [
    [1, 2, 4]
]
vertices = 3

Erwartete Ausgabe:
expected = -1
Eingabe:
std::vector<std::vector<long long>> links = {
    {1, 2, 4}
};
long long vertices = 3;

Erwartete Ausgabe:
long long expected = -1;
Eingabe:
long[][] links = new long[][] {
    new long[] {1, 2, 4}
};
long vertices = 3;

Erwartete Ausgabe:
long expected = -1;

Erläuterung

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

So gehst du vor

Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.

Hinweis 1

Du brauchst eine günstigste Menge an Verbindungen, die trotzdem jeden Knoten verbunden hält, also einen Spannbaum.

Hinweis 2

Füge gierig die billigste Verbindung hinzu, die keinen Zyklus erzeugt, oder baue Komponenten mit einer Union-Find-Struktur auf.

Hinweis 3

Wenn weniger als Knoten minus eins nutzbare Verbindungen den Graphen verbinden, ist die Antwort unmöglich.

Erwartete Komplexität

Zeit O(links log links), zusätzlicher Speicher O(vertices + links)

Referenzen

Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.