103302024-03-31 10:41:18szilHegyi levegőcpp17Accepted 100/100916ms122424 KiB
#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int MAXN = 600'000;
const pair<int, int> DIR[4] = {{0, 1}, {1, 0}};

vector<vector<int>> a;
int p[MAXN], s[MAXN], t[MAXN], d[MAXN];
int n, m, q;

int to_index(int i, int j) {
	return (i-1)*m+j;
}

int holvan(int u) {
	return p[u] == u ? u : holvan(p[u]);
}

void unio(int u, int v, int w) {
	u = holvan(u); v = holvan(v);
	if (u == v) return;
	if (s[u] < s[v]) swap(u, v);
	s[u] += s[v];
	t[v] = w;
	p[v] = u;
}

int calc_depth(int u) {
	if (d[u] == -1) {
		if (p[u] == u) d[u] = 0;
		d[u] = 1 + calc_depth(p[u]);
	}
	return d[u];
}

int query(int u, int v) {
	int ans = 0;
	while (u != v) {
		if (d[u] > d[v]) swap(u, v);
		ans = max(ans, t[v]);
		v = p[v];
	}
	return ans;
}

int main() {
	ios::sync_with_stdio(0); cin.tie(0);
	cin >> n >> m >> q;
	iota(p, p+MAXN, 0);
	fill(s, s+MAXN, 1);
	fill(d, d+MAXN, -1);
	a.resize(n+1, vector<int>(m+1));
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
		}
	}
	vector<array<int, 3>> edges;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			for (auto [dx, dy] : DIR) {
				int nx = i+dx, ny = j+dy;
				if (1 <= nx && nx <= n && 1 <= ny && ny <= m) {
					int w = max(a[i][j], a[nx][ny]);
					int p = to_index(i, j), q = to_index(nx, ny);
					edges.push_back({w, p, q});
				}
			}
		}
	}
	sort(edges.begin(), edges.end());
	for (auto [w, u, v] : edges) {
		unio(u, v, w);
	}
	for (int i = 1; i <= n*m; i++) {
		calc_depth(i);
	}
	while (q--) {
		int a, b, c, d; cin >> a >> b >> c >> d;
		int p = to_index(a, b), q = to_index(c, d);
		cout << query(p, q) << "\n";
	}
	return 0;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted8ms16180 KiB
2Accepted8ms16420 KiB
subtask219/19
3Accepted13ms17244 KiB
4Accepted14ms17696 KiB
5Accepted14ms17852 KiB
6Accepted14ms17900 KiB
7Accepted13ms18096 KiB
8Accepted13ms18188 KiB
9Accepted13ms18392 KiB
10Accepted12ms18624 KiB
subtask320/20
11Accepted7ms17472 KiB
12Accepted8ms18056 KiB
13Accepted18ms18960 KiB
14Accepted145ms31780 KiB
15Accepted572ms80660 KiB
subtask420/20
16Accepted570ms80624 KiB
17Accepted605ms122016 KiB
18Accepted711ms72164 KiB
19Accepted722ms72856 KiB
20Accepted720ms72916 KiB
subtask531/31
21Accepted210ms41376 KiB
22Accepted228ms31588 KiB
23Accepted222ms31508 KiB
24Accepted226ms31404 KiB
25Accepted202ms32176 KiB
26Accepted215ms31424 KiB
27Accepted229ms31424 KiB
28Accepted207ms32188 KiB
29Accepted194ms32012 KiB
subtask610/10
30Accepted804ms122424 KiB
31Accepted913ms72916 KiB
32Accepted916ms73628 KiB
33Accepted893ms73596 KiB
34Accepted762ms81692 KiB
35Accepted836ms76524 KiB
36Accepted827ms72536 KiB
37Accepted879ms72512 KiB
38Accepted765ms81748 KiB
39Accepted694ms76732 KiB