>Link
ybtoj提高模拟赛A组Day7T2
>Description
给出一个 l ∗ w ∗ h l*w*h l∗w∗h的立方体,以及每个坐标的模糊值,相邻两个的格子的模糊值差距在 m m m之内就会连成同一个连通块,问一共有多少个连通块
>解题思路
这道题就是二维变三维,特殊处理一下坐标和相邻的格子的坐标,由于数据范围很小,可以直接暴力每个格子,然后并查集处理连通块就行了
也可以BFS做这道题
>代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 60
using namespace std;
/*const int tx[6] = {0, 1, 0, -1, 0, 0};
const int ty[6] = {0, 0, 0, 0, -1, 1};
const int tz[6] = {1, 0, -1, 0, 0, 0};*/
const int tx[3] = { 0, 0, 1 }, ty[3] = { 0, 1, 0 }, tz[3] = { 1, 0, 0 };
int l, w, h, m, a[N][N][N], c[N * N * N], ans;
int getnum(int x, int y, int z) { return (x - 1) * w * h + (y - 1) * h + z; }
int find(int x) {
if (c[x] == x)
return x;
return c[x] = find(c[x]);
}
int main() {
freopen("engineer.in", "r", stdin);
freopen("engineer.out", "w", stdout);
scanf("%d%d%d%d", &l, &w, &h, &m);
for (int x = 1; x <= l; x++)
for (int y = 1; y <= w; y++)
for (int z = 1; z <= h; z++) scanf("%d", &a[x][y][z]);
for (int i = 1; i <= l * w * h; i++) c[i] = i;
int xx, yy, zz, u, v, ku, kv;
for (int x = 1; x <= l; x++)
for (int y = 1; y <= w; y++)
for (int z = 1; z <= h; z++) {
for (int i = 0; i < 3; i++) {
xx = x + tx[i], yy = y + ty[i], zz = z + tz[i];
if (xx < 1 || xx > l || yy < 1 || yy > w || zz < 1 || zz > h)
continue;
if (abs(a[x][y][z] - a[xx][yy][zz]) > m)
continue;
u = getnum(x, y, z), v = getnum(xx, yy, zz);
ku = find(u), kv = find(v);
if (ku != kv)
c[ku] = kv;
}
}
for (int i = 1; i <= l * w * h; i++) ans += c[i] == i;
printf("%d", ans);
return 0;
}