103292024-03-31 10:39:49szilHegyi levegőcpp17Accepted 100/100958ms265992 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}, {0, -1}, {1, 0}, {-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
1Accepted8ms15908 KiB
2Accepted8ms16252 KiB
subtask219/19
3Accepted10ms17096 KiB
4Accepted13ms17544 KiB
5Accepted13ms17872 KiB
6Accepted13ms18156 KiB
7Accepted13ms18176 KiB
8Accepted13ms18508 KiB
9Accepted13ms18576 KiB
10Accepted10ms18912 KiB
subtask320/20
11Accepted7ms17832 KiB
12Accepted8ms18032 KiB
13Accepted17ms19548 KiB
14Accepted123ms28304 KiB
15Accepted455ms70408 KiB
subtask420/20
16Accepted439ms75448 KiB
17Accepted467ms121472 KiB
18Accepted717ms96972 KiB
19Accepted797ms103320 KiB
20Accepted755ms107952 KiB
subtask531/31
21Accepted190ms74028 KiB
22Accepted230ms72988 KiB
23Accepted231ms76668 KiB
24Accepted236ms80624 KiB
25Accepted181ms80008 KiB
26Accepted215ms87752 KiB
27Accepted231ms91504 KiB
28Accepted181ms90912 KiB
29Accepted194ms98864 KiB
subtask610/10
30Accepted691ms183208 KiB
31Accepted938ms166752 KiB
32Accepted958ms181052 KiB
33Accepted936ms193368 KiB
34Accepted663ms193280 KiB
35Accepted822ms218156 KiB
36Accepted820ms227740 KiB
37Accepted897ms240084 KiB
38Accepted642ms240972 KiB
39Accepted703ms265992 KiB