Retour aux défis
Difficile 0 résolus 0 % de réussite

Minimum Network Connection Cost

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

Ce que vous allez apprendre

  • Connecter un graphe à moindre coût avec Kruskal
  • Détecter les cycles avec une structure union-find
  • Signaler quand un graphe ne peut pas être connecté

Problème

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.

Contraintes

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.

Exemples

Exemple 1
Entrée :
links = [
    [1, 2, 4],
    [2, 3, 2],
    [1, 3, 7]
]
vertices = 3

Sortie attendue :
expected = 6
Entrée :
std::vector<std::vector<long long>> links = {
    {1, 2, 4},
    {2, 3, 2},
    {1, 3, 7}
};
long long vertices = 3;

Sortie attendue :
long long expected = 6;
Entrée :
long[][] links = new long[][] {
    new long[] {1, 2, 4},
    new long[] {2, 3, 2},
    new long[] {1, 3, 7}
};
long vertices = 3;

Sortie attendue :
long expected = 6;

Explication

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

Exemple 2
Entrée :
links = [
    [1, 2, 4]
]
vertices = 3

Sortie attendue :
expected = -1
Entrée :
std::vector<std::vector<long long>> links = {
    {1, 2, 4}
};
long long vertices = 3;

Sortie attendue :
long long expected = -1;
Entrée :
long[][] links = new long[][] {
    new long[] {1, 2, 4}
};
long vertices = 3;

Sortie attendue :
long expected = -1;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Il vous faut un ensemble de liens le moins cher possible tout en gardant tous les sommets connectés, ce qui suggère un arbre couvrant.

Indice 2

Ajoutez de façon gloutonne le lien le moins cher qui ne crée pas de cycle, ou faites grandir les composantes avec une structure union-find.

Indice 3

S’il y a moins de liens utiles que vertices moins un pour connecter le graphe, la réponse est impossible.

Complexité attendue

temps O(links log links), espace supplémentaire O(vertices + links)

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.