#include "validation.h" using namespace std; typedef long long ll; typedef long double ld; typedef pair ii; typedef vector vi; typedef vector vvi; typedef vector vvvi; typedef vector vvvvi; typedef vector vii; #define x first #define y second #define pb push_back #define eb emplace_back #define all(v) (v).begin(), (v).end() // Checks that the output is "impossible" if and only if this is the answer, // checks whether the reported maximal distance matches the answer, and finally // whether the reported optimal position has (at most) this maximal distance. vvi A; ll h, w; vvvi D; ll dfs(ll i, ll j, ll t) { if (D[j][i][t] != -2) return D[j][i][t]; D[j][i][t] = -1; if (A[j][i] == t) return D[j][i][t] = 0; ll bi, bj, ba = -100000000; for (ii p : vii{ii{i+1, j}, ii{i, j+1}, ii{i-1, j}, ii{i, j-1}}) { if (p.x >= 0 && p.x < w && p.y >= 0 && p.y < h) { ll a = A[p.y][p.x]; if (abs(a - t) < abs(ba - t) || (abs(a - t) == abs(ba - t) && abs(a - A[j][i]) < abs(ba - A[j][i]))) { ba = a; bi = p.x; bj = p.y; } } } ll r = dfs(bi, bj, t)+1; if (r == 0) r = -1; D[j][i][t] = r; return r; } int main(int argc, char **argv) { // Set up the input and answer streams. std::ifstream in(argv[1]); std::ifstream ans(argv[2]); // Only for custom checker. OutputValidator v(argc, argv); string s; ans >> s; if (s == "impossible") { v.test_string("impossible"); v.newline(); return 0; } in >> h >> w; ll a, r; ll ra; a = v.read_integer("a", 1, h*w); v.space(); r = v.read_integer("r", 2, h*w); v.newline(); ans >> ra; v.check(r == ra, "Reported distance is not correct."); ll x, y; A = vvi(h, vi(w, 0)); D = vvvi(h, vvi(w, vi(h*w+1, -2))); for (ll j = 0; j < h; j++) { for (ll i = 0; i < w; i++) { in >> A[j][i]; if (A[j][i] == a) { x = i; y = j; } } } for (ll t = 1; t <= h*w; t++) { ll rt = dfs(x, y, t); v.check(rt >= 0 && rt <= r, "Reported distance does not equal actual distance."); } }