From e20f0bb2b3c5d21aafa702be5680bc9becae9bf1 Mon Sep 17 00:00:00 2001 From: Powfu <1875065753@qq.com> Date: Wed, 27 Dec 2023 10:58:02 +0000 Subject: [PATCH] =?UTF-8?q?add=202101040022/chapter=5F8/=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E6=89=80=E6=9C=89=E7=82=B9=E7=9A=84=E6=9C=80=E5=B0=8F=E8=B4=B9?= =?UTF-8?q?=E7=94=A8.cpp.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Powfu <1875065753@qq.com> --- ...0\345\260\217\350\264\271\347\224\250.cpp" | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 "2101040022/chapter_8/\350\277\236\346\216\245\346\211\200\346\234\211\347\202\271\347\232\204\346\234\200\345\260\217\350\264\271\347\224\250.cpp" diff --git "a/2101040022/chapter_8/\350\277\236\346\216\245\346\211\200\346\234\211\347\202\271\347\232\204\346\234\200\345\260\217\350\264\271\347\224\250.cpp" "b/2101040022/chapter_8/\350\277\236\346\216\245\346\211\200\346\234\211\347\202\271\347\232\204\346\234\200\345\260\217\350\264\271\347\224\250.cpp" new file mode 100644 index 00000000..979bc629 --- /dev/null +++ "b/2101040022/chapter_8/\350\277\236\346\216\245\346\211\200\346\234\211\347\202\271\347\232\204\346\234\200\345\260\217\350\264\271\347\224\250.cpp" @@ -0,0 +1,59 @@ +void swap(int* a, int* b) { + int tmp = *a; + *a = *b, *b = tmp; +} + +struct Edge { + int len, x, y; +}; + +int cmp(struct Edge* a, struct Edge* b) { + return a->len - b->len; +} + +int find(int* f, int x) { + return f[x] == x ? x : (f[x] = find(f, f[x])); +} + +int unionSet(int* f, int* rank, int x, int y) { + int fx = find(f, x), fy = find(f, y); + if (fx == fy) { + return false; + } + if (rank[fx] < rank[fy]) { + swap(&fx, &fy); + } + rank[fx] += rank[fy]; + f[fy] = fx; + return true; +} + +int minCostConnectPoints(int** points, int pointsSize, int* pointsColSize) { + int n = pointsSize; + struct Edge edges[(n + 1) * n / 2]; + int edgesSize = 0; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + edges[edgesSize].x = i; + edges[edgesSize].y = j; + edges[edgesSize++].len = fabs(points[i][0] - points[j][0]) + fabs(points[i][1] - points[j][1]); + } + } + qsort(edges, edgesSize, sizeof(struct Edge), cmp); + int f[n], rank[n]; + for (int i = 0; i < n; i++) { + f[i] = i; + rank[i] = 1; + } + int ret = 0, num = 1; + for (int i = 0; i < edgesSize; i++) { + if (unionSet(f, rank, edges[i].x, edges[i].y)) { + ret += edges[i].len; + num++; + if (num == n) { + break; + } + } + } + return ret; +} \ No newline at end of file -- Gitee