Example 1 — Enumerate every spanning tree
Four vertices, five edges; try every 3-edge subset and keep the acyclic ones.
#include <stdio.h>
struct Edge { int u, v, w; };
static int find(int p[], int x) {
while (p[x] != x) x = p[x];
return x;
}
int main(void) {
struct Edge e[] = {{0, 1, 1}, {1, 2, 2}, {0, 2, 3}, {2, 3, 4}, {1, 3, 6}};
int count = 0, best = 1000;
for (int i = 0; i < 5; i++)
for (int j = i + 1; j < 5; j++)
for (int k = j + 1; k < 5; k++) {
int p[4] = {0, 1, 2, 3}, pick[3] = {i, j, k}, ok = 1, sum = 0;
for (int t = 0; t < 3; t++) {
int ra = find(p, e[pick[t]].u), rb = find(p, e[pick[t]].v);
if (ra == rb) { ok = 0; break; }
p[ra] = rb;
sum += e[pick[t]].w;
}
if (ok) {
count++;
if (sum < best) best = sum;
}
}
printf("spanning trees found: %d\n", count);
printf("minimum weight: %d\n", best);
return 0;
} How It Works
- Ten 3-edge subsets exist; two contain a cycle (0-1-2 and 1-2-3).
- The other eight each connect all four vertices.
- The cheapest is edges 0-1, 1-2, and 2-3 with weight 1 + 2 + 4 = 7.
