data-structures · intermediate · ~15 min

Minimum spanning tree weight

Prim's (or Kruskal's) MST.

Challenge

Undirected weighted graph (symmetric w; 0 = no edge, positive = weight).

int mst_weight(const int *w,int n);

Return the total weight of a Minimum Spanning Tree, or −1 if the graph is disconnected.

Input format

w n×n symmetric, weights ≥1 or 0.

Output format

MST total weight, or −1.

Constraints

n>=1; single vertex → 0.

Starter code

#include <stddef.h>
/* Total weight of a Minimum Spanning Tree of an UNDIRECTED weighted graph (symmetric w; 0 = no edge, positive = weight). Return -1 if the graph is disconnected. */
int mst_weight(const int *w,int n){ (void)w;(void)n; return -1; }

Common mistakes

Not detecting disconnection; adding an edge that reconnects an already-in-tree vertex.

Edge cases to handle

Disconnected → −1; single vertex → 0.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.