1. Kruskal's Algorithm with Explicit Edge Generation
Intuition
Generate all possible edges between every pair of points (u, v) with Manhattan weight |x_u - x_v| + |y_u - y_v|. There are V(V-1)/2 edges. Sort all edges ascending by weight and use Disjoint Set Union (DSU) to greedily pick non-cycle-forming edges until V - 1 edges have been included.
Algorithm
- Create an edge list containing all pairs (i, j) with weight |x_i - x_j| + |y_i - y_j| for 0 <= i < j < n.
- Sort the edge list in ascending order of weight.
- Initialize DSU with n elements.
- Iterate through sorted edges; for each edge (u, v, w), check if find(u) != find(v). If true, union them, accumulate w, and increment edge count.
- Stop once n - 1 edges are added and return the total cost.
#include <iostream>#include <vector>#include <cmath>#include <numeric>#include <algorithm> struct Edge { int u, v, weight; bool operator<(const Edge& other) const { return weight < other.weight; }}; class DSU { std::vector<int> parent;public: DSU(int n) : parent(n) { std::iota(parent.begin(), parent.end(), 0); } int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } bool unite(int i, int j) { int rootI = find(i); int rootJ = find(j); if (rootI != rootJ) { parent[rootI] = rootJ; return true; } return false; }}; int minCostConnectPoints(std::vector<std::vector<int>>& points) { int n = points.size(); std::vector<Edge> edges; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int dist = std::abs(points[i][0] - points[j][0]) + std::abs(points[i][1] - points[j][1]); edges.push_back({i, j, dist}); } } std::sort(edges.begin(), edges.end()); DSU dsu(n); int totalCost = 0, count = 0; for (const auto& edge : edges) { if (dsu.unite(edge.u, edge.v)) { totalCost += edge.weight; if (++count == n - 1) break; } } return totalCost;} int main() { std::vector<std::vector<int>> points = {{0,0},{2,2},{3,10},{5,2},{7,0}}; std::cout << "Min Cost: " << minCostConnectPoints(points) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(V^2 log V) where V is points.length. Generating V(V-1)/2 edges and sorting them dominates. - Space complexity:
O(V^2) auxiliary memory to store all V(V-1)/2 edges in an explicit edge list.