|
| 1 | +```cpp |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <vector> |
| 5 | +#include <algorithm> |
| 6 | +#include <numeric> |
| 7 | +using namespace std; |
| 8 | +using ll = long long; |
| 9 | + |
| 10 | +int M, N, Q; |
| 11 | + |
| 12 | +int r[250000]{}, H[500][500]{}; |
| 13 | +vector<vector<pair<int, int>>> V(250000); |
| 14 | +int dep[250000]{}, par[250000][18]{}, cost[250000][18]{}; |
| 15 | + |
| 16 | +int f(int x) { return x == r[x] ? x : r[x] = f(r[x]); } |
| 17 | +int coord(int x, int y) { return x * M + y; } |
| 18 | + |
| 19 | +void makeTable() { |
| 20 | + for (int k = 1; k < 18; k++) for (int i = 0; i < N*M; i++) { |
| 21 | + par[i][k] = par[par[i][k - 1]][k - 1]; |
| 22 | + cost[i][k] = max(cost[i][k - 1], cost[par[i][k - 1]][k - 1]); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +void dfs(int n, int p, int d) { |
| 27 | + par[n][0] = p, dep[n] = d; |
| 28 | + for (auto[i, c] : V[n]) if (i != p) { |
| 29 | + cost[i][0] = c; |
| 30 | + dfs(i, n, d + 1); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +int solve(int a, int b) { |
| 35 | + int res = 0; |
| 36 | + if (dep[a] < dep[b]) swap(a, b); |
| 37 | + int diff = dep[a] - dep[b]; |
| 38 | + for (int i = 0; i < 18; i++) if (diff & (1 << i)) { |
| 39 | + res = max(res, cost[a][i]); |
| 40 | + a = par[a][i]; |
| 41 | + } |
| 42 | + |
| 43 | + while (par[a][0] != par[b][0]) { |
| 44 | + for (int i = 17; i >= 0; i--) if (par[a][i] != par[b][i]) { |
| 45 | + res = max({ res, cost[a][i], cost[b][i] }); |
| 46 | + a = par[a][i]; |
| 47 | + b = par[b][i]; |
| 48 | + } |
| 49 | + } |
| 50 | + if (a != b) res = max({ res, cost[a][0], cost[b][0] }); |
| 51 | + |
| 52 | + return res; |
| 53 | + |
| 54 | +} |
| 55 | + |
| 56 | +int main() |
| 57 | +{ |
| 58 | + cin.tie(0)->sync_with_stdio(0); |
| 59 | + |
| 60 | + cin >> N >> M >> Q; |
| 61 | + |
| 62 | + iota(r, r + N * M, 0); |
| 63 | + vector<tuple<int, int, int>> E; |
| 64 | + for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { |
| 65 | + cin >> H[i][j]; |
| 66 | + int cur = coord(i, j); |
| 67 | + if (i > 0) E.emplace_back(max(H[i - 1][j], H[i][j]), cur, coord(i - 1, j)); |
| 68 | + if (j > 0) E.emplace_back(max(H[i][j - 1], H[i][j]), cur, coord(i, j - 1)); |
| 69 | + } |
| 70 | + |
| 71 | + sort(E.begin(), E.end()); |
| 72 | + for (auto[c, a, b] : E) { |
| 73 | + int x = f(a), y = f(b); |
| 74 | + if (x == y) continue; |
| 75 | + V[a].emplace_back(b, c); |
| 76 | + V[b].emplace_back(a, c); |
| 77 | + r[x] = y; |
| 78 | + } |
| 79 | + |
| 80 | + dfs(0, -1, 0); |
| 81 | + makeTable(); |
| 82 | + |
| 83 | + for (int a, b, c, d; Q--;) { |
| 84 | + cin >> a >> b >> c >> d; |
| 85 | + int s = coord(a - 1, b - 1), e = coord(c - 1, d - 1); |
| 86 | + |
| 87 | + if (s == e) cout << H[a - 1][b - 1] << '\n'; |
| 88 | + else cout << solve(s, e) << '\n'; |
| 89 | + } |
| 90 | + |
| 91 | +} |
| 92 | + |
| 93 | +``` |
0 commit comments