|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#define MAX 50 |
| 3 | + |
| 4 | +using namespace std; |
| 5 | +using pii = pair<int, int>; |
| 6 | + |
| 7 | +vector<vector<pii>> state; |
| 8 | +bool visited[MAX][MAX]; |
| 9 | +int arr[MAX][MAX]; |
| 10 | +int total[MAX * MAX]; |
| 11 | +int n, l, r; |
| 12 | +const int dy[4] = {0, 0, 1, -1}, dx[4] = {1, -1, 0, 0}; |
| 13 | + |
| 14 | +inline bool check(int y, int x) |
| 15 | +{ |
| 16 | + return x >= 0 && n > x && y >= 0 && n > y; |
| 17 | +} |
| 18 | + |
| 19 | +void rec(int id, int y, int x) |
| 20 | +{ |
| 21 | + visited[y][x] = true; |
| 22 | + if (state.size() == id) |
| 23 | + { |
| 24 | + state.push_back(vector<pii>()); |
| 25 | + } |
| 26 | + state[id].push_back(make_pair(y, x)); |
| 27 | + total[id] += arr[y][x]; |
| 28 | + for (int i = 0; i < 4; i++) |
| 29 | + { |
| 30 | + int ny = y + dy[i]; |
| 31 | + int nx = x + dx[i]; |
| 32 | + if (check(ny, nx) && !visited[ny][nx]) |
| 33 | + { |
| 34 | + int dif = abs(arr[y][x] - arr[ny][nx]); |
| 35 | + if (dif >= l && dif <= r) |
| 36 | + { |
| 37 | + rec(id, ny, nx); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +inline void clear() |
| 44 | +{ |
| 45 | + for (int i = 0; i < n; i++) |
| 46 | + { |
| 47 | + for (int j = 0; j < n; j++) |
| 48 | + { |
| 49 | + visited[i][j] = false; |
| 50 | + total[i * (n - 1) + j] = 0; |
| 51 | + } |
| 52 | + } |
| 53 | + state.clear(); |
| 54 | +} |
| 55 | + |
| 56 | +int main() |
| 57 | +{ |
| 58 | + ios::sync_with_stdio(false); |
| 59 | + cin.tie(nullptr); |
| 60 | + cout.tie(nullptr); |
| 61 | + bool check = true; |
| 62 | + int i, j, d, res = 0; |
| 63 | + cin >> n >> l >> r; |
| 64 | + for (i = 0; i < n; i++) |
| 65 | + { |
| 66 | + for (j = 0; j < n; j++) |
| 67 | + { |
| 68 | + cin >> arr[i][j]; |
| 69 | + } |
| 70 | + } |
| 71 | + while (check) |
| 72 | + { |
| 73 | + d = 0; |
| 74 | + for (i = 0; i < n; i++) |
| 75 | + { |
| 76 | + for (j = 0; j < n; j++) |
| 77 | + { |
| 78 | + if (!visited[i][j]) |
| 79 | + { |
| 80 | + rec(d, i, j); |
| 81 | + d += 1; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + check = false; |
| 86 | + for (i = 0; i < state.size(); i++) |
| 87 | + { |
| 88 | + int size = state[i].size(); |
| 89 | + if (size == 1) |
| 90 | + { |
| 91 | + continue; |
| 92 | + } |
| 93 | + bool is_same = true; |
| 94 | + int val = total[i] / size; |
| 95 | + for (j = 0; j < size; j++) |
| 96 | + { |
| 97 | + if (arr[state[i][j].first][state[i][j].second] != val) |
| 98 | + { |
| 99 | + is_same = false; |
| 100 | + arr[state[i][j].first][state[i][j].second] = val; |
| 101 | + } |
| 102 | + } |
| 103 | + if (!is_same) |
| 104 | + { |
| 105 | + check = true; |
| 106 | + } |
| 107 | + } |
| 108 | + if (check) |
| 109 | + { |
| 110 | + clear(); |
| 111 | + res += 1; |
| 112 | + } |
| 113 | + } |
| 114 | + cout << res; |
| 115 | + return 0; |
| 116 | +} |
0 commit comments