Submission #687681

#TimeUsernameProblemLanguageResultExecution timeMemory
687681NK_The Kingdom of JOIOI (JOI17_joioi)C++17
100 / 100
1784 ms119320 KiB
// Success consists of going from failure to failure without loss of enthusiasm
#include <bits/stdc++.h>
 
using namespace std;
 
#define nl '\n'

int d[123];
long long read() {
	char ch = getchar();
	while (ch < '0' || ch > '9') {
		ch = getchar();
	}
	long long v = 0;
	while ('0' <= ch && ch <= '9') {
		v = v * 10 + (int) (ch - '0');
		ch = getchar();
	}
	return v;
}
 
void write(int x) {
	int len = 0;
	while (x > 0) {
		d[len++] = x % 10;
		x /= 10;
	}
	for (int i = len - 1; i >= 0; i--) {
		putchar('0' + d[i]);
	}
	if (len == 0) {
		putchar('0');
	}
	putchar('\n');
}
 
int main() {
	cin.tie(0)->sync_with_stdio(0);
	
	int N = read(), M = read();
	vector<vector<int>> A(N, vector<int>(M)); for(auto& v : A) for(auto& x : v) x = read();
 
	vector<int> U; 
	vector<array<int, 3>> I;
	for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) {
		U.push_back(A[i][j]);
		I.push_back({A[i][j], i, j});
	}
 
	sort(rbegin(I), rend(I));
	sort(begin(U), end(U));
	U.erase(unique(begin(U), end(U)), end(U));
 
	auto solve = [&]() {
		vector<vector<int>> P(N, vector<int>(M));
		vector<int> JOI;
		for(auto i : I) P[i[1]][i[2]] = i[0];
 
		for(int i = 0; i < N; i++) for(int j = 0; j < M; j++) {
			if (i != 0) P[i][j] = min(P[i][j], P[i-1][j]);
			if (j != 0) P[i][j] = min(P[i][j], P[i][j-1]);
		}
 
		JOI = U;
 
		int ans = int(1e9);
		int mn = ans, mx = -ans;
		for(int i = 0; i < int(size(I)); i++) {
			int j = i;
			while(j < int(size(I)) && I[i][0] == I[j][0]) {
				int r = I[j][1], c = I[j][2];
				mn = min(mn, P[r][c]);
				j++;
			}
			mx = max(mx, I[i][0]);
			JOI.pop_back();
 
			if (size(JOI) == 0) break;
 
			// cout << I[i][0] << endl;
 
			// for(auto x : JOI) cout << x << " ";
			// cout << endl;
 
			// for(auto x : IOI) cout << x << " ";
			// cout << endl;
 
			int res = max(JOI.back() - JOI.front(), mx - mn);
			// cout << range(JOI) << " " << range(IOI) << endl;
			ans = min(ans, res);
			i = j-1;
		}
 
		return ans;
	};
 
	int ans = int(1e9);
	for(int f1 = 0; f1 < 2; f1++) {
		for(int f2 = 0; f2 < 2; f2++) {
			// cout << 2 * f1 + f2 << nl;
			ans = min(ans, solve());
 
			for(auto &i : I) i[2] = M - 1 - i[2];
		}
 
		for(auto &i : I) i[1] = N - 1 - i[1];
	}
	 
	write(ans);
 
 
 
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...