[HDU - 5253]连接的管道
克鲁斯卡尔(最小生成树)
#include <stdio.h> #include <math.h> #include <iostream> #include <algorithm> #include <math.h> #include <stdlib.h> #include <string.h> using namespace std; #define maxn 1005 int n, m; int a[maxn][maxn]; int father[maxn * maxn]; struct Edge { int u; int v; int w; }edge[2 * maxn * maxn]; int Find(int x) { return father[x] == x ? x : father[x] = Find(father[x]); } int cmp(Edge a,Edge b) { return a.w < b.w; } int kruscal(int m) { sort(edge + 1, edge + m, cmp); int ans = 0; for(int i = 1; i < m; i++) { int x = Find(edge[i].u); int y = Find(edge[i].v); if(x != y) { father[x] = y; ans += edge[i].w; } } return ans; } int main() { int tcase; scanf("%d", &tcase); int t = 1; while (tcase--) { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { father[i * m + j] = i * m + j; scanf("%d", &a[i][j]); } } int id = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int u = i * m + j; if (i > 0) { int v = (i-1) * m + j; edge[id].u = u; edge[id].v = v; edge[id++].w = abs(a[i][j] - a[i-1][j]); } if (j > 0) { int v = i*m+j-1; edge[id].u = u; edge[id].v = v; edge[id++].w = abs(a[i][j] - a[i][j-1]); } } } int ans = kruscal(id); printf("Case #%d:\n%d\n", t++, ans); } }