1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| const int MAXN = 1000 + 50; int fa[MAXN];
int getFather(int x){ if (fa[x] == x) return x; return fa[x] = getFather(fa[x]); }
bool mergeFather(int x, int y){ int fx = getFather(x), fy = getFather(y); if (fx == fy) return false; if (fx > fy) swap(fx, fy); fa[fx]= fy; return true; }
struct Edge{ int x, y, w; Edge(){} Edge(int x0, int y0, int w0){ x = x0; y = y0; w = w0; } }edge[MAXN * MAXN];
bool cmp(const Edge &a, const Edge &b){ return a.w < b.w; }
class Solution { public: int minCostConnectPoints(vector<vector<int>>& points) { int n = points.size(), m = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) edge[m++] = Edge(i, j, abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])); sort(edge, edge + m, cmp);
for (int i = 0; i < n; i++) fa[i] = i;
int ans = 0, cnt = n; for (int i = 0; i < m && cnt > 1; i++){ int x = edge[i].x, y = edge[i].y, w = edge[i].w; if (mergeFather(x, y)){ ans += w; --cnt; } } return ans; } };
|